Truthy and Falsy

Grade 4, page 4 of 11. A one-minute read.

Here's something interesting. The condition inside an if doesn't have to be an actual boolean. You can put any value in there, and JavaScript will decide whether it counts as "true-ish" or "false-ish."

Values that count as false are called falsy. There are only eight of them, so you can actually memorize this list:

Falsy valueWhat it is
falseThe boolean false
0The number zero
-0Negative zero (yes, that exists)
0nBigInt zero
""The empty string
nullDeliberately empty
undefinedNot given a value
NaNNot a Number

Everything else is truthy. Every non-empty string, every number except zero, every list, every object. All truthy.

JavaScript
if ("hello") {
  console.log("Non-empty strings are truthy");
}

if (42) {
  console.log("Non-zero numbers are truthy");
}

if ("") {
  console.log("You will never see this");
}

if (0) {
  console.log("Or this");
}

It prints

Non-empty strings are truthy
Non-zero numbers are truthy

You can see whether something is truthy or falsy by converting it with Boolean():

JavaScript
console.log(Boolean("pizza"));
console.log(Boolean(""));
console.log(Boolean(0));
console.log(Boolean(-5));
console.log(Boolean(null));

It prints

true
false
false
true
false

Why is this useful?

It lets you write short, readable checks. For example, "did the user actually type something?"

JavaScript
const username = "";

if (username) {
  console.log(`Hello, ${username}!`);
} else {
  console.log("Please enter a username.");
}

It prints

Please enter a username.

Since the empty string is falsy, if (username) means "if the username isn't empty." Neat!

Watch outSneaky truthy strings

"0" and "false" are truthy! They're non-empty strings. It doesn't matter what characters are inside; any string with at least one character is truthy. So if a value comes from a prompt or a form, it's a string, and "0" will count as true. Convert it with Number() first if you want to treat it as a number.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning