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 ?
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.
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With