var name produces strange result in Javascript [duplicate]
Lets say we have this code segment :
var name = ["Apples","Oranges","Strawberries"];
console.log(name.length);
This code produces this weird result of 27 !! The issue seems to be with using the variable name as 'name' which seems like a reserved keyword.
But can anyone explain why this weird behavior ?
Solution 1:
It refers to window.name
, which is the name of the window.
You can use the window's name to target hyperlinks, but it's not typically useful.
More info on window.name
: https://developer.mozilla.org/en-US/docs/Web/API/Window.name
Just testing in chrome:
You can't stop var name
from being window.name
, which is a string. No matter what you set the value to, it will be cast as a string so that it is a valid window name. So, name.length
is the amount of characters in the string. It's best to avoid variable or be very careful about them!
As I can see from some of the other comments, this is an odd concept if you're new to it. The concern is over what window.name
refers to. window.name
is the name of the window. Any use of it is naming the window.
Defending that Chrome's behavior is logical:
If this var document = 'foo'
did what it looks like it would do, you would have overwritten window.document
- the document object - with a string. That would be quite the problem. name
is a property of window
just like document
and has a use that shouldn't be (and can't be in Chrome) replaced.
Solution 2:
In the global scope, when you do var name = ["Apples","Oranges","Strawberries"];
, it's the same as window.name = ["Apples","Oranges","Strawberries"];
.
window.name
must be a string, so it assign ["Apples","Oranges","Strawberries"].toString()
to it which is "Apples,Oranges,Strawberries"
.
Solution 3:
What is the scope of variables in JavaScript? is a good start. Basically, when you're declaring name
outside of a function, you're actually hiding the window.name
value, which is a very, very bad idea (be very careful about any global variables you declare - they are actually values of the window
object - including hiding existing values.
As others have said, the fact that Google Chrome forces the type to string is probably a Chrome quirk (although somewhat understandable), but the underlying cause is that you're simply doing something "dangerous" you didn't realize you're doing :)