DevPath · Learn to code ESPTEN

Conditionals

Truthy/falsy and the ternary operator

Truthy and falsy values

Here is a trick you will use every day. The condition of an if does not have to be a comparison: JavaScript can look at any value and decide whether it "counts as true". There is a short list of falsy values (they behave like false) and everything else is truthy. You only have to memorize the short list; the rest falls into place by elimination.

Falsy values (only these six, you'll know them by heart in a minute):

false
0
""        // empty string
null
undefined
NaN       // "Not a Number": result of an invalid numeric operation

NaN (Not a Number) appears when a numeric operation has no valid result, for example Number("hello") or 0 / 0. It is of type number, but it represents "not a valid number", and it is falsy.

Examples:

if ("hello") console.log("strings with text are truthy");
if (0) console.log("this does NOT run");
if ([]) console.log("an empty array is truthy!");

That truthy empty array catches everyone off guard the first time, watch out. This idea is pure gold for checking at a glance whether a variable "has something inside":

const name = "";
if (name) {
  console.log("Hello " + name);
} else {
  console.log("Name is missing"); // runs: "" is falsy
}

The ternary operator

It is the pocket-sized if/else: an if/else that fits on a single line and returns a value. When you just want to pick between two options for a variable, it saves you four lines. Its syntax is:

condition ? valueIfTrue : valueIfFalse
const age = 20;
const message = age >= 18 ? "Adult" : "Minor";
console.log(message); // "Adult"

It is ideal for simple assignments. But don't get carried away nesting ternaries inside ternaries: if you have to squint to read it, go back to the good old if/else. Readability wins every time.

Examples

Did the user fill in their name? (truthy)

const user = "";
if (user) {
  console.log("Welcome, " + user);
} else {
  console.log("Anonymous user");
}

Player level based on points (ternary)

const points = 80;
const level = points >= 50 ? "advanced" : "beginner";
console.log("Level:", level);
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← if, else if and elseThe switch structure →