Stop using Loose Equality in JavaScript
Discovering the Problem
In JavaScript, there are two common methods to compare values:
The difference between the two is that loose equality performs type conversion, while strict equality does not. For example, 1 == '1'
converts the string to a number before comparison, thus returning true
, while 1 === '1'
strictly compares the types, returning false
.
So what potential problems can this small difference cause?
Using loose comparisons can make the conditions in your code ambiguous. For instance, in the following code, it is clear that 0
and ''
are not equal. However, because loose comparison is used, this coding style makes the code less rigorous, so it is recommended to use strict comparison.
0 == ''; // true0 == '0'; // true0 == false; // true
Summary
Whenever possible, use ===
instead of ==
. It’s better to write stricter conditions from the start. Since ==
does not check types, it often leads to bugs due to JavaScript’s automatic type conversion. For example:
const a = 1;const b = '1';
typeof a; // Numbertypeof b; // String
a == b; // truea === b; // false
// In terms of type, a and b are different, but JavaScript converts them during comparison, so using === is a stricter requirement for "types to be the same."
In most cases, you won’t want to use loose equality, but in certain situations, it might be more convenient, such as when comparing null
and undefined
, because their values are equal but their types are different. In this case, using ==
can be more convenient, allowing you to check both null
and undefined
at once:
// Write a condition: when a is null or undefined, it will enter the if statement.
// Using loose comparisonif (a == null) {}// Using strict comparisonif (a === null || a === undefined) {}
For a detailed comparison of the differences between the two, you can refer to the MDN documentation: Understanding Equality Comparison which is very comprehensive.