More fun with ‘==’ and ‘===’

JavaScript does type coercion when doing comparisons

'0' == 0 evaluates to true

because the string gets coerced to a number.

Remembering our issues with ‘truthy’ and ‘falsy’ we may sometimes wish to use === which evaluates the expression based on both the value and the type of the two sides:

'0' === 0 evaluates to false

(because the items are different types)

Using our friend the unary operator can force the string into a number type before the comparison is made. So:

+'0' === 0 evaluates to true

Other fun expressions:

-1 == '-1' evaluates to true
-1 === '-1' evaluates to false
-1 === +'-1' evaluates to true
-1 === -'-1' evaluates to false
-1 === -'1'  evaluates to true

What the Heck is the ‘+’ for?

I came across the following that someone had added to some code I was working on:

incidentId = +idValue;

I initially thought this was something to do with jQuery (because of the single initial punctuation). Remember, this blog’s goal is to document my experiences in learning how to do stuff in JavaScript, not to make me look smart.

It turns out that it’s the same old unary operator we’re used to seeing in more ‘normal’ (less flexible) languages. What this tells the runtime is to treat the value in idValue as a number. Often, we are passing around strings which contain numbers and JavaScript is good at converting stuff for us. If we were to pass idValue in the above code as a string “1”, then the following

idValue + 2

might be calculated as “12” depending on the context, whereas:

+idValue + 2

would always be the number 3.