Use === Instead of ==

Many JavaScript programmers, including your humble author, often repeat the mistake of comparing using ==, which is the type-coercion non-strict equality operator. Let’s look at an example that shows why using == may be a bad idea.

 //BROKEN CODE
 const​ a = ​'1'​;
 const​ b = 1;
 const​ c = ​'1.0'​;
 
 console.log(a == b);
 console.log(b == c);
 console.log(a == c);

In the short piece of code, the constants a, b, and c have values ’1’, 1, and ’1.0’, respectively. One value is of number type and the other two are of string type. The last three lines compare each combination of the constants. Suppose a is equal to b and b is equal to c; then logically JavaScript should tell us that a is equal to c. But the JavaScript == operator does not honor the transitive property of equality, due to type coercion, as we see in the output produced by running the code:

 true
 true
 false

The == operator performs type coercion if the things being compared are not of the same type. If the objects or values being compared are both of type string, number, or boolean, then a direct equality check is performed.

When comparing a with b and b with c, type coercion was involved before the comparison. However, when a and c were compared, a lexical comparison was used. Hence we see a different result than what we may otherwise expect.

In the uncommon situation where you want type coercion before comparison for equality, then == is your operator. One situation where == may be a better choice than === is when you want to determine if a variable is either null or undefined—the check variable == null will yield true if variable is null or undefined and may be used instead of variable === null || variable === undefined.

In most of the situations, however, we generally would want a straight up strict equality check, with no type coercions. In that case, use === instead of ==. Let’s rework the previous example using the identity strict equality operator—that is, ===.

 const​ a = ​'1'​;
 const​ b = 1;
 const​ c = ​'1.0'​;
 
 console.log(a === b);
 console.log(b === c);
 console.log(a === c);

We replaced all uses of == with ===. We’re asking JavaScript to perform comparison without any coercions, and it reports all three comparisons as false—consistently the same result for all three comparisons.

 false
 false
 false

Just like the way we should most likely use === instead of == to check if two instances are equal, use !== instead of != to check inequality.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.165.247