0

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?

0

1 Answer 1

-1

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]);

Sign up to request clarification or add additional context in comments.

7 Comments

Or just don't use var, use let or const
Or don't use it in the global scope
@Olian04 sure :) but what if OP isn't using environment which doesn't support let and const
@Bergi yeah :) but i will go with using a name other than name :)
So that means name is restricted in global scope. Thanks everyone
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.