JavaScript lesson · 18 min
JavaScript Truthy and Falsy Values
Understand how JavaScript treats values as true or false inside conditions.
What you will practice
- Recognize common falsy values.
- Use Boolean to inspect truthiness.
- Avoid accidental condition bugs.
What this means
JavaScript conditions do not only work with the literal values `true` and `false`. Many values are treated as true-like or false-like when they appear inside `if (...)`.
Falsy values include `false`, `0`, an empty string, `null`, `undefined`, and `NaN`. Most other values are truthy.
Truthy/falsy rules are convenient, but they can surprise beginners. Sometimes it is better to write a more explicit comparison.
If this is your first time seeing this
Truthy/falsy is JavaScript's shortcut for treating values as yes or no.
This shortcut is useful, but it can surprise you when `0`, an empty string, or an empty array is involved.
Mini glossary
- Truthy
- A value JavaScript treats as true in a condition.
- Falsy
- A value JavaScript treats as false in a condition.
- Boolean
- A true/false value, or a function that shows how a value behaves as true or false.
Example from everyday life
Truthy and falsy values are like a quick yes/no check at a door. An empty guest name means no entry, but a real name means continue. The guard is not reading a full profile; they are doing a quick presence check.
How it works step by step
- The code creates several values that might appear in real UI state.
- `Boolean(value)` shows how JavaScript treats each value in a condition.
- The empty name becomes false because an empty string is falsy.
- The array is truthy even when it has no items, so the code checks `items.length` explicitly.
Where you will use this
- A form checks whether a required text field is empty.
- A page chooses whether to show a loading state or real data.
- A search result list checks `items.length` instead of checking only the array itself.
Before you run the code
Truthy/falsy is useful for quick presence checks, but be careful with numbers and empty arrays.
When the exact value matters, write the exact comparison you mean instead of relying on truthiness.
Common beginner mistakes
- Thinking an empty array is falsy. It is actually truthy.
- Treating `0` as missing data when 0 may be a valid number.
- Using truthiness when an explicit comparison would be clearer.
Run the code to see console output here.
Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Change `name` to `"Mira"` and run again.
- Add one item to the array and check `Has items`.
- Try `Boolean(null)` and `Boolean(undefined)`.