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
  • 13,671
  • 6
  • 23
  • 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
  • 377,238
  • 77
  • 533
  • 578
2

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

Tim Pote
  • 27,191
  • 6
  • 63
  • 65
2

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

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
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,539
  • 10
  • 64
  • 107