var name produces strange result in Javascript

javascript, variables

Solution

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.

Problem

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 ?

Original source

Related problems