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 (or anything else) will convert it to Boolean first, (!x
is same as !Boolean(x)
) so the strict comparison can succeed. (actually, using ! on anything will coerce it to a Boolean in JS)
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With