How “100″ != 100

We’re all probably used to the usual comparison methods in different languages. After all, if you learned some sort of Math, you know == is a rather common comparison operator in some programming languages. Javascript has it too, but some of the comparisons done in Javascript sometimes produces rather ambiguous results. Don’t believe me? Fire up your Firebug console and try the expressions in the first table below.

Expression Result
undefined == null true
NaN == NaN false
0 == false true
1 == true true
2 == true false
0 == undefined false
0 == null false
‘100′ == 100 true

So, what happened in the last case? The string 5 is definitely not the same as the integer 5. But, apparently some conversion happens under the hood while comparing.

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers; if either operand is a string, the other one is converted to a string
Mozilla Developer Center

In cases like this, especially in Javascript since it’s a loosely typed language, it is better to use the strict comparison operator. In case you’re wondering what a strict comparison operator, instead of using “==” and “!=”, you will use “===” and “!==” respectively. By using the strict comparison operator, Javascript does not perform any conversion and compares both the operands values and types.

Now, here’s the same expressions as above using the strict equality operator and check out the different results in some cases.

Expression Result
undefined === null false
NaN === NaN false
0 === false false
1 === true false
2 === true false
0 === undefined false
0 === null false
‘100′ === 100 false

Leave a Reply




You may use the tags listed below in your comments:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Published in
Tagged under
Some other categories