Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain this Javascript quirk

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.

like image 868
Teodor Sandu Avatar asked Feb 02 '26 01:02

Teodor Sandu


1 Answers

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.

like image 140
Daniel A. White Avatar answered Feb 03 '26 17:02

Daniel A. White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!