! next to a number in a conditional prints true on strict comparison

  • A+
Category:Languages
console.log(false === 0) // false  console.log(false === !1) // true, why does it equate to true using !? 

and vice versa for

console.log(true === 1 ) // false  console.log(true === !0) // true 

I understand the difference between equality and identity but couldn't understand this behaviour of JS . Please explain ?

 


The === requires that both values are the same type, no implicit coercion is performed.

When you compare a boolean to a number with triple ===, you will always get false, since they are not the same type.

But using ! in front of a number will convert it to Boolean first, (!x is same as !Boolean(x)) so the strict comparison can succeed.

Rules of conversion number-to-boolean conversion :

For the number-to-boolean conversion, 0 and NaN are coerced to false, and any non-zero number is coerced to true. (FYI, null, undefined and the empty string '' are the only other falsy values in JS)

Now, you will have two boolean to compare, and === will return true or false accordingly.

So, to summarize :

in !1, 1 is non-zero, so it gets coerced to true, and !true gives false

so false === !1 is equivalent to false === false, which is a true statement.

You can work out the details for the other comparison.


As an additional resource, if you have time and are interested in learning more, I recommend the very good free ebook "You don't know JS".

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: