3

Someone I know is just learning programming and stumbled upon this and left me baffled:

Please open a console (Chrome/Firefox) and type: var name = ['what', 'the', '...?'];

I would expect name to be an array of strings, but:

  • typeof name displays string instead of Array
  • listing the name variable prints a string instead of an array
  • name.length is 13 instead of 3
  • writing name = name.split(',') returns an array ["what", "the", "...?"] as expected, but name is still a string, not an array

name is the only variable name that seems to behave this way, or at least I couldn't find another one.

Is this just a console quirk, a JavaScript engine bug, or what?

NOTE: the above happens on Chrome and Firefox. IE Edge surprisingly works as expected (typeof name is Array and all that). Not tested on other browsers.

1

1 Answer 1

6

window.name is a global which is a string in the DOM.

Notice you can get around it by declaring the variable in a function scope:

(function() {
   var name = ['foo', 'bar'];
   console.log(typeof name);
})();

As for why IE/Edge is different - its their interpretation of the spec and likely has been that way for years. Changing it now would be a breaking change.

Sign up to request clarification or add additional context in comments.

2 Comments

so why in Edge that doesn't happen ?!!
Actually the default window.name seems to be a property with a setter that turns any value it's being assigned into a string. If you delete window.name then try again, you'll get an array as expected. @DanielA.White please update your answer to include this. Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.