We as a js developer often used "==" and "===" operators in js, but few of us knows about diff b/w them,
"==" (Equality Operator):
The "==" operator is used for loose equality comparison. It checks whether the operands are equal after performing type coercion if necessary. Type coercion means converting the operands to a common type before comparison.
console.log(5 == '5'); // true
console.log(true == 1); // true
"===" (Strict Equality Operator):
The "===" operator is used for strict equality comparison. It checks whether the operands are strictly equal without performing type coercion. Both the values and the types of the operands must match for the comparison to return true.
console.log(5 === '5'); // false
console.log(true === 1); // false
But "==" does type coercion, means converting to a common type before comparison. So, is there any hierarchy on which conversion depends?
- If either operand is a
undefined, they are considered equal (unless strict equality is being used with the "===" operator).
- If either operand is a boolean, the boolean is converted to a number (false becomes 0, true becomes 1) before comparison.
- If one operand is a string and the other is a number, the string is converted to a number before comparison.
- If one operand is an object and the other is a primitive value, the object is converted to its primitive value before comparison. This can be done using the
toString()methods of the object.
- If the operands are both strings, they are compared as strings.
It's important to note that the type coercion process can sometimes lead to unexpected or non-intuitive results, which is why it's generally recommended to use the strict equality operator "===" instead of the loose equality operator "==". The strict equality operator does not perform type coercion and requires both the values and the types to match for the comparison to return true.
Follow #rounitsinha for more 😝