Software Developer and GNU/Linux specialist

Double- versus triple-equals comparators in Javascript

If you’ve never run across the distinction between double-equal and triple-equal comparators, don’t worry. You will sooner or later, because they appear in several languages. Here I’d like to focus on Javascript, because I believe it characterizes a common distinction between the two types.

In a nutshell (and who was it who said that anything that can be put in a nutshell belongs there?) the distinction is this:

== and != compare and contrast values, coercing data types as needed. === and !== do strict comparison, meaning data types are compared rather than coerced.

But wait, some of you are asking. Javascript doesn’t do the types thing, not really. Numbers can mutate to strings and so forth. Yes, Javascript types are flexible and often easy to translate. That means nothing; the types are still distinct:

typeof false
"boolean"
typeof 1
"number"
typeof "1"
"string"
typeof variable_that_doesnt_exist
"undefined"
typeof undefined
"undefined"
typeof null
"object"
typeof []
"object"

The === comparator (and its inverse) don’t compare values of different data types; in effect,

a === b

is similar to

typeof a == typeof b && a == b

Why is this important?¬†Well, if we’re just fooling around with a prototype or POC or you have tyrannical control over a system, it may not be. But more often than not, we’re dealing with frameworks, libraries, and services that aren’t under our direct control. A library function with multiple return types may mean something very different when it returns 0 instead of false, and if a comparison doesn’t take that into account, subtle errors tend to emerge.

What does this all boil down to? I’m backing up Douglas Crockford here: use triple-equals if you’re at all in doubt. Your colleagues will give you strange looks, but your code will run predictably.

 

Post a Comment

Your email is kept private. Required fields are marked *