Hi! I'm Nathan Hoad


JavaScript: When Type != Type

After attending the JavaScript Meetup last Monday I thought it might be interesting to have a look at a few examples of JavaScript's sometimes unexpected behaviour. I've covered a few things before, like the difference between substr and substring and the problem with parseInt() so here are some other interesting discoveries.

Since the '+' operator exists for strings anything added to a string will be coerced into being a string, numbers included:

3 + 3 // 6
"3" + 3 // 33

The '-' operator, however, doesn't exist for strings so they will be coerced into being numbers, given the opportunity:

"3" - 3 // 0
"3" - - 3 // 6

When comparing two types (in an if statement, for example) JavaScript will attempt to coerce the types to make a match:

1 == true // true, as expected
"0" == 0 // true, as expected

But sometimes, things don't behave as you would expect:

NaN == NaN // false, but
Infinity == Infinity // true

"Infinity" == Infinity // true, but
"true" == true // false

And then there are cases where types that shouldn't match do:

typeof NaN // Number, even tho NaN means 'Not a Number'

So that's just a sample of JavaScript's random behaviour but now when you come across phantom errors you can rest assured that you aren't going crazy; it's just JavaScript

If I just made your day a little better then thank me with a coffee or maybe a a pizza