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");
And still there are only three types of conversion: numeric, string and boolean. coerced to true , no matter if an object or an array is empty or not. Objects are converted to primitives via the internal [[ToPrimitive]] method, which is responsible for both numeric and string conversion.
Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.
Does JavaScript support automatic type conversion? Yes. It's usually called type coercion, but conversion is perfectly accurate.
Implicit coercion happens when JavaScript coerces the value type to the expected type under the hood. This type of coercion happens without the developer noticing. Explicit coercion happens when we want to coerce the value type to a specific type.
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 ─┘
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.
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