Search code examples
javascriptarraysvariablesvariable-names

Javascript array variable when named "name" showing unexpected result when storing strings


I am writing a very simple code for storing strings in an array and then splitting it but apparently the "variable name" seems to have an impact on the results.

I have tried this on Google Chrome console as well as Microsoft edge. Results are the same.

var fullName = "Jonathan Archer";
var name = fullName.split(" ");
console.log(name[0]);

//The output of the above code is : "J"

var userName = fullName.split(" ");
console.log(userName[0]);

//The output of the above code is: "Jonathan"

//Also tried following, also exhibited same behavior as above
var name = ["Jonathan", "Archer"];
var userName = ["Jonathan", "Archer"];
console.log(name[0]);
console.log(userName[0]);

I don't see why these two code snippets are producing different results. Is there any restriction for using "name" as an array name in JavaScript?


Solution

  • Do not use name as variable name, Because it will conflict with window.name

    var fullName = "Jonathan Archer";
    var n = fullName.split(" ");
    console.log(n[0]);
    
    //The output of the above code is : "J"
    
    var userName = fullName.split(" ");
    console.log(userName[0]);
    
    //The output of the above code is: "Jonathan"
    
    //Also tried following, also exhibited same behavior as above
    var n = ["Jonathan", "Archer"];
    var userName = ["Jonathan", "Archer"];
    console.log(n[0]);
    console.log(userName[0]);