Given the type coercion and the performance issue, as a JS newbie, I've always tried to avoid using double equality and opted for triple equality instead.
However, when does it make sense to use double quality?
Given the type coercion and the performance issue, as a JS newbie, I've always tried to avoid using double equality and opted for triple equality instead.
However, when does it make sense to use double quality?
Short answer: it never makes sense to use ==
instead of ===
.
Long answer: while it never makes sense, there are cases where you want to write less code, and you are sure about your input.
==
is not that bad if you really understand what's truthy. There are some gotchas, for example [1] == true
and [2] == false
.
Remember that the principal aim of Javascript was to be an easy language to be used by web designers, that's one of the reasons behind all this stuff you encounter.
As a simple example, as Barmar said, the best approach is to use it to avoid converting data and check equality. Here is another example:
const deleteTodos = _ => {
if (howManyTasksToRemoveInput.value == tasks.length) {
warningLabel.innerHTML = "You can't remove all the list";
} else if (howManyTasksToRemoveInput.value > tasks.length) {
warningLabel.innerHTML = "You DEFINITELY can't remove more tasks than you have";
} else {
tasks.splice(0, +howManyTasksToRemoveInput.value);
}
}
There's one case where there's a clear benefit to using ==
, which is foo == null
: this is true if and only if foo === undefined || foo === null
, a commonly useful test.
Even here, using something like node's isNullOrUndefined(foo)
(which is implemented as return value == null;
!) is a much clearer way to express the intent, if it's not an established practice in the code-base you're working in.
When you want to allow Javascript to convert types automatically. E.g.
if (someElement.value == 3)
value
of an input is always a string. The ==
operator will automatically convert it to a number here, so you don't have to write
if (parseInt(someElement.value) === 3)
You should be careful, since some some of the automatic conversions may not do what you expect.