1

Possible Duplicate:
Why does “,,,” == Array(4) in Javascript?

In JavaScript why does

",,," == new Array(4)

It returns true in Chrome Developer Tools, and nodejs console.

Community
  • 1
  • 1
Bnicholas
  • 12,847
  • 6
  • 22
  • 26

4 Answers4

5
console.log(new Array(4).toString()); // ",,,"

casted to string with above value making both equal.

",,," == ",,," // true

JS sees that on left hand is a string and on right hand side an array which is not good for comparison, it casts array to string and then does the comparison.

Notice that:

log(",,," === new Array(4));

would result in false since === checks not only for value but also type and types are different of course.

Sarfraz
  • 367,681
  • 72
  • 526
  • 573
2

Because the new Array(4) is being implicitly cast to a string, which will equal ",,," (four empty elements, comma separated).

Tim Pote
  • 25,751
  • 6
  • 60
  • 64
2

Because Array(4).toString() returns ",,," - 4 empty elements, so only the commas between them

Maxim Krizhanovsky
  • 25,260
  • 5
  • 51
  • 86
1

An array in String form produces a comma separated list of the elements, ie 1,2,3,4. If there are no elements in the Array, it will show up as ,,,.

(new Array(4)).toString() produces ,,,.

Note that new Array(4) === ",,," returns false.

Wex
  • 15,188
  • 10
  • 59
  • 102