JavaScript == and ===

Part 1

JavaScript == and ===

These two were a mystery to me for quite a while, but the difference is actually fairly simple. They behave as follows:

x == y                 // x and y have the same value
x === y                // x and y have the same value AND type

Say you are reading in a number from a query parameter. Query parameters are strings, so the input will be a string containing a number.

You could use == in this case, and it will convert the string to a number for you:

var num = 10;
var input = "10";

num == input           // true

== converts the value on the right to match the type on the left.

But === doesn’t. The types must match:

num === input          // false

You might think therefore that == is more useful than ===. However it's not really, as some of the conversions == makes are not what you might expect.

For example:

'' == '0'              //  false
'0' == ''              //  true

What the @%#?!

There are lots of other weird and wonderful cases. Because of this, == is usually best avoided. Otherwise, your == condition might occasionally return true when you expected false, or vice versa. These problems can be a nightmare to debug.

In our example, instead of using ==, you could parse the input to convert it to a number:

var inputNum = parseInt(input, 10);

num === inputNum       // true

Or, you could convert number on the left hand side to a string:

var numString = num.toString();

numString === input    // true

Of course, if you know that both variables should have the same type, you can just use === straight away.

The not-equal-to operators != and !== work in a similar way, with != having the same odd cases (but negated). Again, != is usually best avoided. Use !== instead (and make sure the types of the operands match).

Stick with triple equals (=== and !==). Avoid double equals (== and !=).

Leave a comment