Skip to content

Chapter 06

Making Decisions

So far our programs run every line, top to bottom, no matter what. Real programs need to make choices: show a discount if the customer is a member, warn the user if a field is empty. That's what the if statement is for.

The if Statement

An if runs a block of code only when a condition is true. The condition goes in round brackets, and the code to run goes in curly braces { }:

const age = 20;

if (age >= 18) {
  console.log("You are an adult.");
}

JavaScript works out the condition age >= 18. It's true, so the code inside the braces runs. If age were 15, the condition would be false and JavaScript would skip the whole block as if it weren't there.

Otherwise: else

Add an else block to say "and if the condition is false, do this instead":

const age = 15;

if (age >= 18) {
  console.log("You may enter.");
} else {
  console.log("Sorry, you're too young.");
}
// Sorry, you're too young.

Exactly one of the two blocks runs - never both, never neither.

Several Choices: else if

For more than two outcomes, chain conditions with else if. JavaScript checks each in order and runs the first one that's true, then stops:

const score = 75;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 70) {
  console.log("Grade: B");
} else if (score >= 50) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}
// Grade: B

Order matters. Because 75 is checked against 90 first (false), then 70 (true), it prints "B" and skips the rest. The final else catches everything that matched nothing above.

Conditions Can Be Anything

The condition is just an expression that comes out true or false, so you can use the logical operators from Chapter 4:

const age = 25;
const hasLicense = true;

if (age >= 18 && hasLicense) {
  console.log("You can drive.");
} else {
  console.log("You cannot drive yet.");
}

Truthiness

A condition doesn't have to be a true/false comparison. JavaScript will treat almost any value as true or false when it needs to. Empty and "nothing" values count as false; most others count as true. The false-ish ones (called "falsy") are worth memorising:

  • false
  • 0 (the number zero)
  • "" (an empty string)
  • null and undefined

Everything else is "truthy." This lets you write neat checks like "did the user type anything?":

const name = "";

if (name) {
  console.log(`Hello, ${name}`);
} else {
  console.log("Please enter your name.");
}
// Please enter your name.  (an empty string is falsy)
Tip
Read if (name) as "if name has something in it." It's a common, readable shorthand once truthiness clicks.