Type coercion in JS, it's hierarchy?

rounit08

Rounit Ranjan Sinha

Posted on June 16, 2023

Type coercion in JS, it's hierarchy?

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.
For example:
console.log(5 == '5'); // true
console.log(true == 1); // true
In the above examples, the operands are of different types (number and string, boolean and number), but JavaScript automatically converts them to the same type for comparison.

"===" (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.
For example:
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?

Yes, there is a hierarchy for type coercion in JavaScript. The coercion process follows a set of rules:

  1. If either operand is a null or undefined, they are considered equal (unless strict equality is being used with the "===" operator).
  2. If either operand is a boolean, the boolean is converted to a number (false becomes 0, true becomes 1) before comparison.
  3. If one operand is a string and the other is a number, the string is converted to a number before comparison.
  4. 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 valueOf() or toString() methods of the object.
  5. If the operands are both strings, they are compared as strings.

Tip:
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 😝

πŸ’– πŸ’ͺ πŸ™… 🚩
rounit08
Rounit Ranjan Sinha

Posted on June 16, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related