1. Introduction
Equality in JavaScript can be a difficult concept to navigate more so if you are a beginner. You may have come across cases where ===
is used and where ==
is used instead.
Does it matter which one you use? What is the difference? In this article, you will learn the concepts of double equals and triple equals and you will be able to explain what they are, which one to use, and why.
Double Equals (Loose Equality)
The double equals ==
uses loose equality or abstract equality when comparing values. It attempts to resolve the type (with type coercion) if the values are of different types.
It starts by checking the types of values to be compared. If they're not of the same type, it tries to match each other and finally, the comparison happens.
Triple Equals (Strict Equality)
As the name suggests, the triple equals ===
compares the values strictly. It does not attempt to change the type of values. It compares both the values and their types.
If the values are the same and the types are the same, it will return true
. On the other hand, if the values are the same and the types are different, it will return false
.
Examples
The following are some examples to help you better understand how equality works in JavaScript;
· Example 1
const name = "Love"
const nickName = "Love"
console.log(name == nickName) // true
console.log(name === nickName) // true
In our first example both ==
and ===
returns true. This is because the type and value of both name and nickname are the same. In both instances, the type is string and the value is "Love".
· Example 2
const value1 = 23
const value2 = "23"
console.log(value1 == value2) // true
console.log(value1 === value2) // false
In our second example, the double equals ==
returns true and the triple equals ===
returns false. This is because the values are of different types as value1 is a number and value2 is a string.
The double equals resolve the difference in type. In other words, it changes the type of the string to a number and then compares it. Hence, it returns true.
The triple equal takes into account the differences in types and that is why it returns false.
· Example 3
console.log(0 == " ") // true
console.log(0 === " ") // false
console.log(1 == [1]) // true
console.log(1 === [1]) // false
console.log(true == "1") // true
console.log(true === "1") // false
From the examples above, we can see that whenever the types of values differ, ==
will attempt to match them to be of the same type. The double equals can thus cause some unexpected behaviors in your application.
3. Conclusion
It is widely considered best practice to use strict equality over loose equality. If you need to change type before comparison, it is safer to do it yourself than rely on ==
to do so.
Happy coding!