-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?

1
  • [] == 0 == false == '' - read about loose comparison. also read about === Commented Apr 2, 2018 at 5:54

2 Answers 2

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'.

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

Comments

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

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.