==, and ===. It will cause bugs and errors in the codebase when used incorrectly.
I decided to add the assignment operator to this post because I had made the mistake many times early on of mixing this up with the comparison operators which caused me quite a bit of trouble while testing. So here is a quick explanation of how it is used:
= operator is used to assign values to either
const variables. The value itself can be anything — a
function, another variable, etc.
Loose Comparison Operator
This operator is used to compare values on either side of the
== and the return value is always a boolean (
false). Since the comparison performed is loose, the values can be of different data types, meaning comparing something like
1 == “1” will return
true. This is because the double equals operator will perform a type coercion, which means that the values will be compared after the value on the right is converted to the same data type as the value on the left. After the conversion, we are now comparing
1 == 1.
false == “”
Though you might think this comparison will return
false because the values are completely different, it actually returns
true. Both false and empty strings are considered falsey values, so essentially you are comparing whether
false == false.
“” with each other will return
undefined can only be compared to either themselves or each other to produce a truthy value.
NaN might be the strangest one of all because not only is it not equal to any of the other falsey values, but its also not equal to itself as well.
NaN == NaN returns
Strict Comparison Operator
As the name implies, the
=== operator compares values in a more concise manner. Both the values and the data types must be equal in order to return a truthy value. When you can, utilizing this comparison instead of the double equals
== in your code is a more efficient and precise way to ensure that the values being tested are absolutely truthy (or falsey). Now, with the same example used earlier,
1 === “1” will return false and so will
false === “”.
=== whenever possible to get the values that you would normally expect.