Skip to Content

JavaScript and Equality

A few months back I made a post explaining my new-found appreciation for JavaScript. One conclusion I came to in that post was that just because the syntax is similar to some other language, it doesn’t mean you know it. An example of where I have (painfully) learned this is in the way JavaScript handles equality.
Most programmers are aware of the difference between the c-style assignment operator(= ), and the c-style test for equality ( == ):

foo = 1; // this assigns the value of 1 to foo
foo == 1; // this tests if foo is equal to 1

Since JavaScript’s syntax looks c-style, it is reasonable to assume that you already know how equality works. Unfortunately, soon you would run into these interesting cases that have caused me much grief in the past:

"0" == 0 // TRUE
"0" == false // TRUE
" 0 " == 0 // TRUE
"" == false // TRUE
0 == false // TRUE

These all evaluate to TRUE because JavaScript actually has two tests for equality. It has a coercing test ( == ), and a non-coercing test ( === ). With the coercing test, one or both of the arguments are converted to another type before doing the test. This can result in some bizarre behavior like the examples above. To avoid these cases it is best to always use the non-coercing version.

"0" === 0 // FALSE
"0" === false // FALSE
" 0 " === 0 // FALSE
"" === false // FALSE
0 === false // FALSE
While I think this was a poor design decision by the JavaScript creators (and a clear violation of the Principal of Least Astonishment ), it does illustrate why it is dangerous to assume you know one language just because it looks like another one you already know.
Be the first to leave a comment
You must be Logged on to comment or reply to a post.