1
let x = [];
if(x==0) 
    console.log('Hello')

The about code prints 'Hello'

let x = [ 1 ];
if(x==0) 
    console.log('Hello');

The above code does not print 'Hello'.

Why?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    Many related questions that contain the answer. See [Why does {} == false evaluate to false while \[\] == false evaluates to true?](https://stackoverflow.com/q/27989285/218196) and [If both \[0\] == 0 and 0 == \[\[0\]\] are true than why is \[0\] == \[\[0\]\] false?](https://stackoverflow.com/q/27703580/218196). `[] == 0` and `[] == false` are the same because `false` is converted to `0`. – Felix Kling Jul 14 '17 at 23:42
  • @DenIsahac: How is that a duplicate? – Felix Kling Jul 14 '17 at 23:47
  • 1
    [] is falsy, 0 is falsy. Falsy == Falsy === true. Pretty simple mate. – Mardoxx Jul 14 '17 at 23:49
  • @Mardoxx: Except that `[]` is not falsey. It's not *that* straightforward. Have a look at the links I posted in my first comment. – Felix Kling Jul 14 '17 at 23:51
  • @Mardoxx When objects of different types are compared, one of them is converted to the other type. It doesn't just compare their truthiness. – Barmar Jul 15 '17 at 00:10
  • @Mardoxx For example `true == 3` is false, even though both are truthy. `true` is converted to a number, so it's equivalent to `1 === 3`. – Barmar Jul 15 '17 at 00:12

1 Answers1

1

While I think this should be closed as duplicate of this question, before any more false statements are made:

== performs type conversion. This is the type conversion that takes place according to the Abstract Equality Comparison Algorithm:

[] == 0                    // step 9 ToPrimitve([]) == 0
"" == 0                    // step 5 ToNumber("") == 0
0 == 0                     // step 1.c.iii

[1] == 0                   // step 9 ToPrimitve([1]) == 0
"1" == 0                   // step 5 ToNumber("1") == 0
1 == 0                     // step 1.c.iii

References: ToNumber, ToPrimitive

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143