Reputation: 2890
I guess I kind of know the differences between == and === in JavaScript, it is that == will do type coercion when compare but === will not. I understand the following code will be true:
console.log(true == "1");
but when the code below is false?
console.log(true == "true");
Upvotes: 5
Views: 145
Reputation: 11
The boolean operand is converted into a numeric value and strings are converted into a numeric value since one operand is a number.
We end up with 1 == NaN. If either of the operands is NaN, the equal operator always returns false.
Upvotes: 1
Reputation: 288100
When you loosely compare a boolean with a value of another type, the boolean is coerced into a number.
And when you compare a number and a string, the string is coerced into a number.
The full rules are explained in The Abstract Equality Comparison Algorithm
The process is like this:
true == "true" ─┐
├─ Number(true) // 1
1 == "true" ─┤
├─ Number("true") // NaN
1 == NaN ─┤
├─ // Comparing with `NaN` always produces `false`
false ─┘
Upvotes: 4