1

Is there a reason as to why these statements evaluate to true?

0 == [0];
1 == [1];
5 == [5];
5000 == [5000];
1000000 == [1000000];

So basically any number equals itself wrapped in an array? What's the logic behind this?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Ayyoudy
  • 3,641
  • 11
  • 47
  • 65

4 Answers4

6

That's because the non-strict equality operator coerces both its operands to strings in this case, and the string representation of an array is the elements it contains, delimited by commas:

>>> [1, 5].toString()
"1,5"

Since the arrays in your question only contain one element, their string representation is the same as their element's:

>>> [5000].toString()
"5000"
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
1

[0] is an array with one element "0". So 0 == [0] would be the equivalent of doing:

0 == myArray(0) in another language. Where myArray(0) returns the value at the index 0, which in this case would be 0.

That's my understanding of JavaScript arrays. Someone else may want to jump in and correct me if I'm wrong.

Carl Winder
  • 938
  • 8
  • 18
1

Because == does not compare type of the variable, and === does compare type of the variable, so:

0 == [0]  //true
0 === [0] // false

In the same case:

0 == '0'  //true
0 === '0' //false
Someth Victory
  • 4,492
  • 2
  • 23
  • 27
0

One reason behind this is the operator used is "==" which compares only compares values and not data types as in 1=="1" is true.

Pawan
  • 605
  • 1
  • 6
  • 18