AI Hints
Home›JavaScript Tutorial›More Decisions
JavaScript · Lesson 22 of 138

Truthy and Falsy

What counts as true.

⏱ 2 min read▶ Video at 26:21🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

An if statement doesn't need a real true or false. You can give it any value, and JavaScript decides whether it counts as true. Values that count as false are called falsy. Everything else is truthy.

Truthy and Falsy
From the video: Truthy and Falsy
  • if accepts any value
  • Some count as false
  • Falsy and truthy

The falsy values

There are only a few falsy values. False, zero, an empty string, null, undefined, and NAN. We test each one with a tiny if inside a loop. Run it. Everything else is truthy, even the string zero, and an empty list.

app.jsjavascript
const values = [false, 0, "", null, undefined, NaN, "0", "hi", 42, []];

for (const v of values) {
  if (v) {
    console.log(JSON.stringify(v), "is truthy");
  } else {
    console.log(String(v) || '""', "is falsy");
  }
}
Output
false is falsy
0 is falsy
"" is falsy
null is falsy
undefined is falsy
NaN is falsy
"0" is truthy
"hi" is truthy
42 is truthy
[] is truthy

A handy shortcut

Truthy values make checks short. If name is an empty string, it's falsy, so we greet a guest instead. Or, used with a value, gives the first truthy one, which is a quick way to set a fallback. Run it.

app.jsjavascript
const name = "";

if (name) {
  console.log(`Hello, ${name}`);
} else {
  console.log("Hello, guest");
}

const shown = name || "Anonymous";
console.log(shown);
Output
Hello, guest
Anonymous

Summary

Falsy values are false, zero, empty string, null, undefined, and NAN. Everything else is truthy. Next, the ternary operator.

Key takeaways
  • Six falsy values
  • Everything else is truthy
  • || for fallbacks
Next up: The Ternary Operator — a one-line if