Find a course

Module 2: Operators and DecisionsLesson 4 of 1213 min

Making Decisions with if, else and Logic

Control program flow with if, else if and else, combine conditions with &&, || and !, and use truthy and falsy values and the ternary operator wisely.

Step 1 of 15Learn

Code that chooses

A streaming site shows a "Subscribe" button to visitors and a "Continue watching" button to members. A thermostat turns heating on below 19 °C. A checkout gives free shipping over $50. Every useful program makes decisions, and in JavaScript the main tool is if:

const total = 62;

if (total >= 50) {
  console.log("Free shipping!");
} else {
  console.log("Shipping costs $5.99");
}

The condition in parentheses is evaluated. If it is true, the first block runs; otherwise the else block runs. Exactly one of them runs, never both.

For more than two possibilities, chain else if:

if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else if (score >= 70) {
  grade = "C";
} else {
  grade = "F";
}

JavaScript checks the conditions in order and stops at the first true one. That is why the order matters: if you tested score >= 70 first, a score of 95 would get a C. Put the most specific (or highest) condition first.

Curly braces mark the block of code that belongs to each branch. Always use them, even for one line; it prevents bugs when you add a second line later.

Step 2 of 15Practice · Work it out

What is the value of fee after this code runs? ``js const age = 67; let fee; if (age < 12) { fee = 5; } else if (age >= 65) { fee = 7; } else { fee = 12; } ``

Step 3 of 15Practice · Diagram

An else-if chain checks from the top down

JavaScript tests each condition in order and runs the first branch that is true, then skips the rest.

A student scores 85. Which branch runs?

Tap the shape that answers the question, then press Check.

An else-if chain checks from the top downHierarchy diagram: score, if score >= 90: "A", else if score >= 80: "B", else if score >= 70: "C", else: "F".scoreif score >= 90:"A"else if score >=80: "B"else if score >=70: "C"else: "F"
score
if score >= 90: "A"
else if score >= 80: "B"
else if score >= 70: "C"
else: "F"

Runs only when every condition above was false.

Step 4 of 15Learn

Combining conditions

Real decisions often depend on several facts. Three logical operators combine booleans:

  • && (and): true only if both sides are true. age >= 18 && hasTicket
  • || (or): true if at least one side is true. isWeekend || isHoliday
  • ! (not): flips true and false. !isLoggedIn
const temp = 24;
const raining = false;

if (temp > 20 && !raining) {
  console.log("Picnic time");
}

Short-circuit evaluation: && stops as soon as it finds a false side, and || stops at the first true side. This lets you guard against errors: user && user.name only reads user.name if user exists.

A common mistake is writing if (x === 1 || 2). It reads naturally in English but means "x is 1, or 2 is truthy," which is always true. Write each comparison fully: if (x === 1 || x === 2).

When mixing && and ||, && binds tighter, like multiplication over addition. Add parentheses to make your meaning explicit: (isMember || hasCoupon) && total > 20.

Step 5 of 15Compare

Truth table for && and ||

Aspecta && ba || b
a true, b truetruetrue
a true, b falsefalsetrue
a false, b truefalsetrue
a false, b falsefalsefalse

Step 6 of 15Practice · Sort into groups

With const a = 5, b = 10;, does each condition evaluate to true or false?

Tap an item, then tap its group (or drag it there).

Step 7 of 15Learn

Truthy, falsy and the ternary operator

An if condition does not have to be a boolean. JavaScript converts any value to true or false. Exactly these values are falsy:

false, 0, -0, "" (empty string), null, undefined, NaN (and 0n, the bigint zero)

Everything else is truthy, including "0", "false", [] (an empty array) and {} (an empty object). This lets you write compact checks:

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

That runs the else branch for an empty string, null or undefined. But careful: if a valid value can be 0, such as a quantity, if (quantity) wrongly treats 0 as missing. Test explicitly with quantity !== undefined in that case.

The ternary operator is a one-line if/else that produces a value:

const label = stock > 0 ? "In stock" : "Sold out";

Read it as "condition ? value if true : value if false." It is perfect for choosing between two values. For anything with side effects or more than two outcomes, a regular if statement is clearer.

switch is another option when one value is compared against many exact cases, such as a day name or a menu choice; each case ends with break.

Step 8 of 15Note

Step 9 of 15Practice · Select all that apply

Which of these values are falsy? Select all that apply.

Select all that apply.

Step 10 of 15Practice · Code challenge

Write a function shippingCost(total, isMember) that returns 0 if the customer is a member or the total is at least 50, and otherwise returns 5.99.

Runs in a sandbox in your browser.
  • shippingCost(62, false)
  • shippingCost(20, true)
  • shippingCost(20, false)
  • shippingCost(50, false)

Step 11 of 15Note

Step 12 of 15Practice · Spot the mistake

This grading code gives the wrong grade for a score of 95. Which line is the problem?

Step 13 of 15Note

Step 14 of 15Diagram

Guard clauses: exit early, then do the real work

Guard clauses: exit early, then do the real workProcess diagram: No user? return → Inactive? return → Bad quantity? return → Happy path.No user?returnInactive?returnBadquantity?returnHappy path

Tap a shape with to see more.

No user? return

if (!user) return "No user";

Inactive? return

if (!user.isActive) return "Account inactive";

Bad quantity? return

if (qty <= 0) return "Invalid quantity";

Happy path

Only valid input reaches here, with no extra indentation.

Step 15 of 15Practice · Choose one

What does this expression evaluate to? ``js const items = 0; const message = items ? ${items} items : "Cart is empty"; ``