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:

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

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

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

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

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