1

I played around a bit and created a javascript array containing some strings. When I tried to access the array it behaves quite strangely. The array is created correctly and works as expected if it is called something else.

var name = ["foo", "bar"];

alert(name); // shows "foo,bar"

Why is the array converted into a string, if the variable name is name? According to the standard (which the linked website is based on) it should be a valid variable name: https://mothereff.in/js-variables#name

  • so you answered your own question in less than a minute? nice – omarjmh May 08 '16 at 14:15
  • I found out the answer before asking the question but couldnt find a previous question that asked the same thing and therefore decided to create this question and answer it myself. As far as i know its a common practice on stackoverflow: http://stackoverflow.com/help/self-answer – Florian Richter May 08 '16 at 14:17
  • @JordanHendrix: That's permitted *(there's even a special checkbox for it when you ask a question)*, though this issue has been asked about many times before. –  May 08 '16 at 14:18
  • sorry didn't mean to sound like I didn't 'approve' of it... – omarjmh May 08 '16 at 14:18
  • 1
    There are too many duplicates of this. – Oriol May 08 '16 at 14:18
  • 1
    Seems like i didnt search enough. Sorry for the duplicate. – Florian Richter May 08 '16 at 14:20
  • 1
    [Here's another duplicate](http://stackoverflow.com/questions/28029234/why-global-variable-name-changes-to-string) that deals with arrays like in this question. @FlorianRichter: Not a big deal. –  May 08 '16 at 14:20

1 Answers1

2

If you execute javascript in a browser environment, the code is executed in the window context. This context already has some global variables set. One of those is the window.name which is a string. When the variable is set, the browser will automatically cast the new value to string which causes the strange behavior.

So even though name is a valid variable name, it should not be used in the global context if you are executing your javascript in the browser (It should work fine in e.g. node.js).