Strict vs Loose equality in JavaScript

In this tutorial, you are going to learn the difference between strict === and loose == equality operators in JavaScript and understand how they compare operands.

In JavaScript we use triplet equals === known as strict equality or double equals ==known as loose equality to compare two or more operands, they look similar but they are different.

Strict Equality (===)

When comparing two operands, triple equals=== returns true only if both values and types are identical for the two operands being compared. For instance20 === "20", here we are comparing a number which is 20 to a string which is "20", strict equality returns false because their types are different string and number.

Unlike the above example, let’s compare 20 to20 by using again triple equals. This time around, we are comparing a number to another one. Thus, triple equals operator returns true because both operands have same value and type. More examples are listed below👇 👇 👇

Loose Equality (==)

When using double equals in JavaScript, it performs type coercion . Type coercion means that two values are compared only after attempting to convert them into a common type.

Let’s use loose equality to compare number and string. Let’s say 20 is the value of our number and the string value is "20". In this case, first things first, JavaScript will try to convert our values into a common type . The string value of "20" can easily be converted into the number value of 20. Since 20equals 20, double equals operator returns true. Find more examples below👇 👇 👇

Falsy values with loose equality

There are only six Falsy values in Javascript: false boolean, number zero 0, an empty string "", null, undefined and NaN (Not A Number).

  1. When comparing any of the following falsy values: false, 0and empty string “” with loose equality, they will always be equal! That’s because these values will all coerce into a false boolean.

2. When comparing null and undefined, they are only equal to themselves and each other. To recall, trying to compare null to any other value, it will return false

3. NaN is not equivalent to any value even itself, it will always return false when using loose equality.

Tips:

Unless you absolutely need to use loose equality, otherwise it always better you use strict equality.

That’s all for post, I hope you enjoyed reading it.

Full Stack Software Engineer