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?

6
  • 1
    Many related questions that contain the answer. See Why does {} == false evaluate to false while [] == false evaluates to true? and If both [0] == 0 and 0 == [[0]] are true than why is [0] == [[0]] false?. [] == 0 and [] == false are the same because false is converted to 0. Commented Jul 14, 2017 at 23:42
  • @DenIsahac: How is that a duplicate? Commented Jul 14, 2017 at 23:47
  • 1
    [] is falsy, 0 is falsy. Falsy == Falsy === true. Pretty simple mate. Commented Jul 14, 2017 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. Commented Jul 14, 2017 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. Commented Jul 15, 2017 at 0:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.