Comparing two things for equality can often trip up the unwary JavaScript developer, as the language has several quirks we need to be aware of.
In this article, we’ll look at why that is, exploring both the double and triple equals operators, as well as the concept of truthy and falsy values in JavaScript. By the time you’ve finished reading, you’ll understand how JavaScript makes its comparisons, as well as how truthy and falsy values can help you write cleaner code.
Typing in JavaScript
JavaScript variables are loosely/dynamically typed and the language doesn’t care how a value is declared or changed:
let x; x = 1; // x is a number x = '1'; // x is a string x = [1]; // x is an array
Seemingly different values equate to true
when compared with ==
(loose or abstract equality) because JavaScript (effectively) converts each to a string representation before comparison:
// all true 1 == '1'; 1 == [1]; '1' == [1];
A more obvious false
result occurs when comparing with ===
(strict equality) because the type is considered:
// all false 1 === '1'; 1 === [1]; '1' === [1];
Internally, JavaScript sets a value to one of seven primitive data types:
- Undefined (a variable with no defined value)
- Null (a single null value)
- Boolean (a
true
orfalse
value) - Number (this includes
Infinity
andNaN
— not a number!) - BigInt (an integer value larger than 2^53 – 1)
- String (textual data)
- Symbol (a unique and immutable primitive new to ES6/2015)
Everything else is an Object — including arrays.
Truthy and Falsy Values in JavaScript
As well as a type, each value also has an inherent Boolean value, generally known as either truthy or falsy. Some of the rules are a little bizarre, so understanding the concepts and effect on comparison helps when debugging JavaScript applications.
The following values are always falsy:
false
0
(zero)-0
(minus zero)0n
(BigInt
zero)''
,""
,``
(empty string)null
undefined
NaN
Everything else is truthy. That includes:
'0'
(a string containing a single zero)'false'
(a string containing the text “false”)[]
(an empty array){}
(an empty object)function(){}
(an “empty” function)
A single value can therefore be used within conditions. For example:
if (value) { // value is truthy } else { // value is falsy // it could be false, 0, '', null, undefined or NaN }
document.all
You might also see document.all
listed as a falsy value. This returns an HTMLAllCollection
which contains a list of all of a document’s elements. And while this evaluates to false
in a Boolean context, it’s a deprecated feature and MDN advises against its use.
Continue reading Truthy and Falsy: When All is Not Equal in JavaScript on SitePoint.