The equality operators are part of the comparison operators.
There are four equality operators; these are equal ("=="), not equal ("!="), identically equal ("===") and not identically equal ("!=="). These operators work with two values that don't necessarily have to be numbers, in which case they are converted to numbers behind the scene.
The result of an equality comparison is always a Boolean value (true, false).
The conversions follow these rules:
- If an operand is a Boolean it will be converted to a number and compared properly;
- If only one operand is a string, it will be converted into a number (if possible) and compared regularly;
- If only one operand is an object, it will be converted into a number and compared regularly;
- If both operands are objects, then they are compared to see if they are pointing to the same object, in which case true is returned; otherwise false is returned;
- Values of null and undefined are evaluated as equal and they cannot be converted into any other data type;
- If either operand is NaN the equal operator returns false while the not-equal one returns true.
These are some examples to remember:
if (null == undefined); //true
if (NaN == NaN); //false
if (NaN != NaN); //true
if (100 == NaN); //false
if (true == 1); //true
if (null == 0); //false
if ("100" == 100); //true
In addition to the equal ("==") operator, there is also an identically equal ("===") operator.
The difference between them is that the latter one evaluates the true type of an operand without a data type conversion, while the former one compares operands after the conversion has acted.
These two examples show the difference:
var equalOp = ("100" == 100); //true
var equalOp = ("100" === 100); //false
We can see that the identically equal operator does not convert the string "100" into a number and thus returns false as result.
Following the same principles as above, the not identically equal operator has an exclamation point ("!==") in front of the equal signs, as shown in this example:
var notEqualOp = ("100" != 100); //false
var notEqualOp = ("100" !== 100); //true