Sikau

JavaScript · Day 15 · about 20 min

Truthy and falsy

Why an empty string counts as no.

Is an empty box a yes?

An if doesn't only accept true and false. You can give it any value — a number, a string — and JavaScript decides whether it *counts as* true. This is the secret behind lots of short, tidy code.

The six falsy values

Only a few values count as false. They're called falsy:

  • false
  • 0
  • "" (an empty string)
  • null
  • undefined
  • NaN

Everything else is truthy — including "0", "false", -1 and " " (a space).

const name = "";

if (name) {
  console.log("Hello, " + name);
} else {
  console.log("Please type your name.");
}

console.log(Boolean("momo"));
console.log(Boolean(0));

The empty plate: Ask "is there food on the plate?" An empty plate ("") or zero momos (0) means no. Any amount, even one sad momo, means yes.

The rest of this lesson

  • Truthiness in real codeexplain
  • Predict the outputpredict
  • Truthy or falsy?match
  • A default namepredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript