Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 390
ShadowFax Avatar asked Jan 06 '14 07:01

ShadowFax


2 Answers

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.

like image 62
m59 Avatar answered Oct 01 '22 19:10

m59


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".

like image 20
xdazz Avatar answered Oct 01 '22 18:10

xdazz