Difference between == and ===, that you don't know yet! 🔥

Ali Samir - Feb 22 - - Dev Community

Uncover the distinction between == and === that may still be unfamiliar to you!


When inquiring about the dissimilarity between == and ===, most individuals will assert that == performs loose type checking, while === involves both type and value checking.

This doesn't capture the entire truth.

This is utterly incorrect. ❌


==, or abstract equality, performs type checking as its primary function. In fact, the initial action of == is to conduct type-checking.

What distinguishes == (Abstract Equality) from === (Strict Equality)?

Let's discover together.


== (Abstract Equality) performs four distinct actions when comparing two variables, a and b.

1. Check the datatype of each variable.

  • If the types of both 'a' and 'b' are identical, perform a strict equality check and return the result.
1 == 1;  // Internally return 1 === 1
Enter fullscreen mode Exit fullscreen mode

2. Verify the absence of null and undefined.

  • If a is null and b is undefined, return true

  • If a is undefined and b is null, return true

null == undefined; // true
undefined == null; // true
Enter fullscreen mode Exit fullscreen mode

3. Converting Non-Primitives to Their Primitive Form

  • When comparing non-primitive types such as Objects and arrays using the == (Abstract Equality) operator, they are initially converted to their non-primitive counterparts by invoking the toString() method.
[] == "";  // [ ] will be converted into a string
[].toString() == "";
"" == "";  // true
Enter fullscreen mode Exit fullscreen mode

4. Convert to Number

  • If the variable a is of the Number type, convert variable b to Number by encapsulating it within a Number function call, and subsequently compare the outcomes.

  • Conversely, if the variable b is of the Number type, convert variable a to Number by encapsulating it within a Number function call, and then compare the results.

"1" == 1;   // "1" will be converted into Number
Number("1") == 1
1 == 1   // true
Enter fullscreen mode Exit fullscreen mode

Observing the steps above leads to the conclusion that ==(Abstract Equality) involves type coercion during variable comparison, whereas ===(Strict Equality) does not perform any type coercion.

This constitutes the fundamental distinction between == and ===.


Happy Coding! 🚀

And don’t forget to find me on the web: https://linktr.ee/AliSamir 👋

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .