Javascript === operator

Like most scripting languages, Javascript is not strongly typed. This causes implicit typing to occur when two variables are compared, resulting in some interesting behaviors. A prime example of this is the equality operator ==. For example, if either operand is NaN, then the equality operator returns false. Even if both operands are NaN, the comparison still evaluates to false, because NaN is not equal to NaN (similar to how comparing anything to an ANSI NULL in SQL evaluates to false).

Or consider the following:

var op1 = “”;
var op2 = true;

if (op1 == op2)

The if statement evaluates to false, because op1 is cast to a boolean. Empty strings are converted to false, and non empty strings are converted to true. However…

Var op1 = “0”;
Var op2 = true;

If (op1 == op2)

In this case, the if statement evaluates to false, because “0” is converted to 0, which is not equal to false. If op1 were equal to “1”, then the statement would evaluate true.

To deal with all these caveats and gotchas, Javascript introduced a strictly typed equality operator, ===, and its eqvuivalent inequality operator, !==. These do a strict type comparison, and if the types do not match, the result is false. Thus 0 === “0” evaluates to false. One interesting to note is that null == undefined is true, however null=== undefined is not. This is because null and undefined are not the same type. In order to maintain type integrity in the code, its considered a best practice to use === whenever possible. It also potentially saves on performance, since no implicit casting is performed.

Leave a Reply

Your email address will not be published. Required fields are marked *