1

I was just creating an random array but i fell into an issue when i choose "name" as identifier.

I am writing this code:

var name = ["test", 10, true];
console.log(name);

When i check console then instead of getting an array there it returns a string like "test,10,true"

If i change identifier from "name" to "x" or anything else then it works fine.

Can anyone please let me know what is going on here?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Vikas Sharma
  • 579
  • 1
  • 5
  • 15

2 Answers2

2

You're assigning to window.name, which calls toString() on whatever you give it. You can't use name as a variable name at global scope.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • And following the same idea, if you declare `name` as a `const`(block-scoped) instead of `var` (global scope) it should work fine. – Douglas P. Jun 11 '19 at 02:18
1

The global variable name is equivalent to the window.name property, and this is required to be a string. So your assignment is equivalent to

name = ["test", 10, true].toString();

You have to be careful with global variables, to make sure they don't conflict with window properties, since some of these have special behavior.

Barmar
  • 741,623
  • 53
  • 500
  • 612