Let’s look at them in more detail.
Soft equality only checks for equality in value, not in type.
For example, we can assign the number three to a variable like this:
const a = 3;
We can compare it like so:
> a == 3 true
This works fine, but there are some slight problems with the double equals operator.
Let’s test again with the string
> a == "3" true
As you can see here, the returned output is
true when in reality it should be
a is not a string but a number.
So what happened that we got
Let’s look at some more examples.
" " == 0; << true " " == "0"; << false false == "0"; << true "1" == true; << true "2" == true; << false "true" == true; << false null == undefined; << true
The snippet above shows values that are not equal, yet tend to be reported as being equal.
Unlike soft equality, hard equality checks for both the value and the type. It is also called a stricter equality test and returns
true only if the two elements are the same.
Let’s use the same example as above with hard equality and see how it will behave.
a === 3; << true a === "3"; << false null === undefined << false
As you can see,
a is equal to the number
3, but not equal to the string
3. The hard equality operator also correctly reports that
undefined are two different values.
This is a good question, and the simple and quick answer is that it depends upon your need.
If your program does not need to check for the value type before doing operations (i.e., you’re certain that both sides will still have the same type), you can go for soft equality.
In the other case and by default, I would suggest always go for hard equality. Using soft equality can cause bugs in the program, and it is often difficult to discover them.
View all Courses