← Web basics: HTML, CSS and JavaScript

Decisions with if and else

Compare values and choose what code runs.

Start this lesson

Programs make decisions with if. You give it a condition in parentheses; if the condition is true, the code in the braces runs, otherwise the else part runs. Conditions use comparisons: === (equal), !== (not equal), <, >, <= and >=. You can combine them with && (and: both must be true) and || (or: at least one must be true). For more than two cases, chain else if.

function ticketPrice(age) {
  if (age < 5) {
    return 0;
  } else if (age < 18 || age >= 65) {
    return 4;
  } else {
    return 9;
  }
}

ticketPrice(3);   // 0
ticketPrice(70);  // 4
ticketPrice(30);  // 9

The checks run from top to bottom and the first true one wins. Under 5 is free; children and seniors pay 4; everyone else pays 9.

One = assigns a value; three === compares. Writing if (age = 18) is a classic bug: it sets age instead of checking it.

A comparison itself gives true or false, so return age >= 18; is a neat way to return a yes/no answer.