3

When I make array object named "name", type automatically changes to "String", not "Array". Why?

<body>
  <script>
    console.log('---------------------------------');
    var name1 = ['abc', 'def'];
    console.log(name1);
    console.log(typeof name1);

    console.log('---------------------------------');
    var name = ['ghi', 'jkl'];
    console.log(name);
    console.log(typeof name);
  </script>    
</body>

Result in Chrome(Mac):

---------------------------------
["abc", "def"]
object
---------------------------------
ghi,jkl
string   // <- Why?
wgkoro
  • 33
  • 1
  • 7
  • See also https://stackoverflow.com/questions/21395941/javascript-weird-behavior-with-new-string-object-reference/21396286#21396286 – Bergi Dec 01 '15 at 13:36

1 Answers1

6

https://developer.mozilla.org/en-US/docs/Web/API/Window.name

It is a string, because window.name has a purpose. You are setting the name of the window.

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • It's worth noting that there's a number of these quasi-[reserved names](http://www.javascripter.net/faq/reserved.htm). – tadman Jan 19 '15 at 16:32
  • In other words, you're not setting a global variable, there is no such thing in Javascript. What you're doing is setting the `name` field of the `window` object. You really want to use some scoping - wrap the "variables" (and the code) in another object or function. – Luaan Jan 19 '15 at 16:34
  • 1
    @tadman: There's [more of them](http://jibbering.com/faq/names/unsafe_names.html)… Though properly declared, all of those can serve as *local* variable names. – Bergi Jan 19 '15 at 16:34
  • @bergi By "local" you mean within the context of a function, not the window, correct? – tadman Jan 19 '15 at 16:35
  • @Luaan: No, there are global variables in JavaScript. That those become `window` properties only is a peculiarity of browser environments. – Bergi Jan 19 '15 at 16:36
  • @tadman: Yes exactly, function-scope local. – Bergi Jan 19 '15 at 16:36
  • @Bergi The question is obviously about Javascript in a browser. I think that "a peculiarity of browser environments" that's common to all the browsers counts as "no globals" for all practical purposes :) And of course, whatever the global object is, it's still an object. – Luaan Jan 19 '15 at 16:45
  • Thank you for quick response! I didn't remember about 'window.name'. – wgkoro Jan 19 '15 at 16:56