When writing Javascript code I've typically tried to steer clear of the double equals. This is because I can trust that the triple equals will evaluate strict equality. It seems that there are opposing camps as far as whether the double equals is ever valid, so I wanted to take a deeper dive and better understand the nuance.
The double equals evaluates loose equality. This means it attempts to convert both values to a common type, then compares their values. This allows for comparisons of string numbers to integers and floats, and falsy values of different types.
If you wanted to check if a string contains a number, you could perform the following comparisons:
let x = "123"
console.log(Number(x) == x)
>> true
let y = "ab123"
console.log(Number(y) == y)
>> false
One way to avoid using the double equals to check if a string contains a number is to use the 'isNaN' function. This built-in JS function checks if a value is not a number while avoiding the double equals; it will return true if the value passed is not a number and false if the value is a number. It will evaluate the contents of a string appropriately.
let x = "123"
console.log(isNaN(x))
>> false
let y = "ab123"
console.log(isNaN(y))
>> true
The double equals also allows for comparing the following as equivalent: false, 0, "". Null and undefined also compare as equivalent to each other.
While it may be tempting to simplify code by utilizing a double equals to test equivalence of different types of falsy values, it is also very simple to include multiple conditions in a comparison to satisfy each falsy value you expect may arise.
So instead of writing:
if (x == false) {
...
You could write:
if (x === false || x === 0 || x === "") {
...
If you want to enter the 'if' statement for any falsy value you could write:
if (!x) {
...
Ultimately, through exploring the different use-cases for the double equals I remain unconvinced that I will need to use the double equals in the future. It seems that any time a double equals is practical, the triple equals could be used with slightly more code - but that extra code and strict equality likely makes the program easier to read. Lastly, because the double equals converts both values to a common type before comparing, the triple equals is typically more efficient.
Sources:
Codeburst - Double/Triple Equals
2ality - Strict Equality
Top comments (0)