What does truthy or falsy mean in JavaScript?
Quick answer
In JavaScript, a value is truthy if a conditional treats it as true, and falsy if the conditional treats it as false. The standard falsy values are false, 0, -0, 0n, "", null, undefined, and NaN; browsers also have the special-case document.all. Empty arrays and empty objects are truthy, so use an explicit length check when you mean “not empty.” [S1][S2]
The question, the details, the next step.
A practical checklist
When reading
if (value), identify which falsy values might occur in that variable. [S1]Remember that
" "and"0"are truthy strings; only the empty string is falsy. [S1]Do not use
if (array)to test whether an array has items. Empty arrays are truthy. [S1]Use a direct condition such as
items.length > 0when checking for array entries.Choose an explicit comparison or content check when truthiness is broader than your intention.
A few more useful answers
Is a truthy value the same as `true`?
No. A truthy value is treated like true in a Boolean context, but it can still be a string, number, array, object, or another type. [S2]
Does `if (value)` check whether a variable exists?
It checks whether the value is truthy, not just whether it exists. For example, an existing value of 0 or "" is falsy, while an empty array is truthy. [S1]
What is the quickest way to check whether an array has items?
Use a condition such as items.length > 0. A plain if (items) does not distinguish an empty array from a nonempty one. [S1]
Sources
References used for this guide.
- [S1] Truthy — MDN developer.mozilla.org · Checked
- [S2] Boolean — JavaScript — MDN developer.mozilla.org · Checked
