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 ?
=== 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.
! 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,
NaN are coerced to
false, and any non-zero number is coerced to
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 :
!1, 1 is non-zero, so it gets coerced to
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".