I am confused why this code results with name[0] being equal to "f" instead of "foo". I thought that when I passed ' ' to the split method "foo" would be the result.
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var name = ar[0].split(' ');
console.log(name[0]);
I am confused why this code results with name[0] being equal to "f" instead of "foo". I thought that when I passed ' ' to the split method "foo" would be the result.
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var name = ar[0].split(' ');
console.log(name[0]);
Share
Improve this question
asked Apr 22, 2017 at 3:20
user7904332user7904332
434 bronze badges
2
-
3
Try it with a variable name other than
name
. Or put the code inside a function so thatname
is a local variable. There is a built-in globalwindow.name
property that is always a string, and yourname
is referencing that property, hence your array gets converted to a string and thenname[0]
gets the first character of that string. See also this question. – nnnnnn Commented Apr 22, 2017 at 3:23 - 1 "In browsers there is a global window.name property…". ;-) – RobG Commented Apr 22, 2017 at 3:32
4 Answers
Reset to default 4The variable
name
is reserved in browsers. If you were to go in the developer console (click f12), and typewindow.name
, you would see that it either gives you""
or some other string result.Your previous code
ar[0].split(' ');
is going to return the following array:[ "foo", "bar" ]
but the browser forcibly converts it to a string because your browser is mad at you since you are trying to change the
typeof
of its reserved variable ;), hence the string value"foo,bar"
. You might however get different results on different browsers.And doing
name[0]
to a string value of"foo,bar"
gets the first letter of the string,f
"name" refers to window.name and is in use. so your array bees a string.
Use another variable such as array2
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var name2 = ar[0].split(' ');
console.log(name2[0]);
Wrap it in a function, you will get exactly result because name refer to window.name
(function () {
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var name = ar[0].split(' ');
console.log(name[0]);
})()
You should avoid using the name
as a variable, as this is an existing JavaScript built-in objects, properties, and methods. Your code should work after you rename the variable name
to anything else, check the code belopw.
Your var name = ar[0].split(' ');
returns an array of substrings.
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var changeThisVariableName = ar[0].split(' ');
console.log(changeThisVariableName[0]);