-2
Code:   
a=[1,2];   
b=[];

if(b==0){    
    console.log('0')    
}  
if(a==2){   
    console.log('2')  
}  
if([]==0){  
console.log('3')  
}  

Output:  
0  
3

in case if [ ] is considered as an array of length 0 and == is comparing [ ] to its length.Why is [1,2]==2 false?

guru
  • 284
  • 2
  • 10

2 Answers2

0

It's not comparing against the length of the array, it's calling the valueOf function of the object, which (I think) is the same as arr.join('').

console.log(String([].valueOf()) === '');
console.log(String([1, 2].valueOf()) === '1,2');

The first one results in '', which is loosely equal to 0.

The second one results in '1,2'.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

the == will do some conversation before do the comparison

   
console.log([] == false) // true
console.log(0  == false) // true 
console.log([] == 0)     // true

also I suggest you read this question and its answers

Ali Faris
  • 17,754
  • 10
  • 45
  • 70