2020-06-04
|~2 min read
|212 words
One of the most challenging things when getting started with Javascript is understanding comparisons.
To do so requires understanding a few things:
==
, and Strict Equality Comparison, i.e. ===
.First, let’s start with the falsey values. There are six and only six:
false
null
undefined
0
NaN
""
(or ''
or “)Everything else is truthy.
if (false || null || undefined || 0 || NaN || "") {
console.log("something in the list is true")
} else {
console.log("everything is false")
}
In the above example, you’ve probably guessed (correctly) that “everything is false” will print.
Now that that’s out of the way, let’s look at the differences between the comparison.
Despite the popular phrasing that ===
checks both value and type whereas ==
only checks type, it’s not quite right.
In fact, if you look at the spec, you’ll see the big difference is that ==
allows coercion of types. This is why 1 == '1'
is true but not 1==='1'
.
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!