Lesson 2
Truthy and falsy
Build a practical mental model for truthy and falsy and use it in working JavaScript.
By the end, you will be able to…
- Explain truthy and falsy in your own words
- Use truthy and falsy in a small program
- Recognize and debug a common failure mode
Build the mental model
JavaScript treats exactly six values as falsy: false, 0, "", null, undefined, and NaN. Everything else — including "0", empty arrays, and empty objects — is truthy, which surprises almost everyone once.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
if (value) is everywhere in real code; knowing precisely what counts as falsy prevents bugs where an empty array or the string "0" is treated as 'nothing'.
Real-world example
A common bug: checking if (items.length) works, but if (items) on an empty array is always true and hides the real check you meant to write.
Common mistakes
- Assuming an empty array or object is falsy
- Assuming the string "0" is falsy because the number 0 is
- Using if (value) when you actually meant to check value.length
Try it yourself
Challenge
Write isEmpty(value) that correctly reports whether an array has no items, without confusing it with falsy.
Knowledge check
Which of these values is truthy in JavaScript?
Summary
Memorize the six falsy values (false, 0, "", null, undefined, NaN); everything else is truthy.