CodeRigor

LESSON

Make decisions with if and else

Compare values, read true and false, choose between blocks of code with if, else if and else, and combine conditions with && and ||.

Every program so far ran the same statements each time. A program becomes useful when it can do different things for different input: let one rider on and turn another away, or say whether a guess was too high. This lesson shows how a program chooses.

Conditions are true or false

A comparison asks a question about two values. The answer is one of two special values, true or false. These two values have their own type, called boolean.

JavaScript
console.log(5 > 3);
console.log(5 < 3);
console.log(5 === 5);
console.log(5 !== 5);

This prints true, false, true and false. The comparison operators are:

Operator Meaning
> greater than
< less than
>= greater than or equal to
<= less than or equal to
=== equal to
!== not equal to

"Equal to" is written with three equals signs, because a single = is already taken: it assigns a value to a name. JavaScript also has a two-sign ==, which quietly converts values before it compares them and gives surprising answers. Always write === and !==.

Strings can be compared too. "yes" === "yes" is true, and "yes" === "Yes" is false, because capital letters count.

An expression that is either true or false is called a condition.

if runs a block only when its condition is true

An if statement has a condition in round brackets and then a block: a group of statements between curly brackets { }. The block runs when the condition is true. When it is false, the block is skipped.

JavaScript
const temperature = 30;
if (temperature > 25) {
  console.log("It is hot.");
  console.log("Drink some water.");
}
console.log("Have a good day.");

This prints all three lines. Change 30 to 20 and run it again: only Have a good day. is printed, because that statement comes after the block and runs either way.

The statements inside the block are moved to the right by two spaces. This is called indenting. JavaScript does not need it; the curly brackets mark the block. People do need it, to see at a glance which statements belong to the if.

else gives the other path

Add else and a second block to say what happens when the condition is false. Exactly one of the two blocks runs.

JavaScript
const age = 15;
if (age >= 18) {
  console.log("You may vote.");
} else {
  console.log("You may not vote yet.");
}

This prints You may not vote yet., because 15 >= 18 is false.

Two paths, and exactly one of them runs
start / 4
The condition is checked once. True leads to the first block, false to the else block. Afterwards both paths join again and the program carries on.
Two paths, and exactly one of them runs
The condition is checked once. True leads to the first block, false to the else block. Afterwards both paths join again and the program carries on.

else if chooses between several paths

For more than two paths, put else if with another condition between the first block and the else. JavaScript checks the conditions from the top and runs the block of the first one that is true. The rest of the chain is skipped, even if a later condition would also be true.

JavaScript
const temperature = 18;
if (temperature > 25) {
  console.log("hot");
} else if (temperature > 15) {
  console.log("mild");
} else {
  console.log("cold");
}
console.log("done");

This prints mild and then done. Step through the diagram to follow the checks.

Checking a chain from the top
start / 4 ⇄ code
With temperature at 18 the first condition is false and the second is true. Its block runs and the else is never considered.
Checking a chain from the top
With temperature at 18 the first condition is false and the second is true. Its block runs and the else is never considered.

Order matters. If the chain asked temperature > 15 first, a temperature of 30 would print mild, because that condition is true and the first true condition wins. Put the narrowest case first.

Take care at the edges. temperature > 25 is false when the temperature is exactly 25. If 25 should count as hot, write temperature >= 25. Whenever you write a comparison, ask what should happen at the exact value.

Combining conditions

Three operators build larger conditions from smaller ones:

  • a && b is true when both sides are true. Read it as "and".
  • a || b is true when at least one side is true. Read it as "or".
  • !a is true when a is false. Read it as "not".
JavaScript
const age = 10;
const height = 130;
console.log(age >= 8 && height >= 120);
console.log(age >= 12 || height >= 120);
console.log(!(age >= 12));

This prints true three times. The first line needs both comparisons to hold, and they do. The second needs one of them, and the height comparison holds. The third turns the false age >= 12 into true.

Each side of && and || must be a complete comparison. To ask whether age is between 8 and 12, write age >= 8 && age <= 12.

Decisions on what the user typed

Typed input is text, so convert it before you compare it with a number.

JavaScript
const typed = "18";   // stands in for a typed line
console.log(typed === 18);
console.log(Number(typed) === 18);

This prints false and then true. The string "18" and the number 18 are different values, so === says they are not equal. This gives no error message: the program quietly takes the wrong path.

Three errors you will meet

One equals sign instead of three.

JavaScript
const age = 20;
if (age = 18) {
  console.log("exactly 18");
}
Text
/work/main.js:2
if (age = 18) {
        ^

TypeError: Assignment to constant variable.
    at Object.<anonymous> (/work/main.js:2:9)

A single = assigns, so line 2 tries to give age a new value, and age is a const. The ^ points at the =. Write === to compare. This is one more reason to prefer const: with let, the same mistake gives no message, changes age to 18 and runs the block every time.

A missing closing curly bracket.

JavaScript
const age = 20;
if (age >= 18) {
  console.log("adult");
Text
main.js:4



SyntaxError: Unexpected end of input

"Unexpected end of input" means the program text stopped while Node was still waiting for something: here, the } that closes the block. The line number is one past the last line, because that is where Node gave up. Look upwards from there for a { without its partner.

Missing round brackets around the condition.

JavaScript
const age = 20;
if age >= 18 {
  console.log("adult");
}
Text
main.js:2
if age >= 18 {
   ^^^

SyntaxError: Unexpected identifier 'age'

An identifier is a name. Node expected ( after if and found the name age instead. The condition of an if always goes in round brackets.

What you can do now

You can compare values, predict whether a condition is true or false, choose between two or more paths, and combine conditions with &&, || and !. In the exercises you will trace which block runs, then write the program that decides who may go on a theme-park ride.

Next: repeat steps with loops, so that a program can do something many times.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →