Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array equal to zero but not itself

I've been playing around with arrays in JavaScript and cannot figure out why this happens:

console.log(0 == 0)
//true

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

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

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

console.log([] == ![])
// true

The empty array is equal enough to zero both left and right, but why isn't it equal to itself?

I realise that comparing two objects would not result true, but why are they coerced to 0 (or falsy, which shouldn't be the case) if you compare them to 0, while threated as an object if you compare them to the other array?

like image 683
Randy Avatar asked Dec 18 '22 10:12

Randy


1 Answers

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

You are trying to compare object with an integer, so your object is implicitly typecasted to equivalent integer value that is 0

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

as two objects are never equal

like image 148
Achal Saini Avatar answered Feb 09 '23 01:02

Achal Saini