Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Full-Stack Web Development — Alpha School

Lesson 10: Decisions and Loops: Controlling Flow

A program that runs the same instructions in the same order every time is not very useful. Real programs make decisions, choosing what to do based on what they find, and repeat work, doing the same steps many times without writing them out many times. Those two abilities, decisions and loops, are called control flow, and they are the same in almost every programming language, so learning them in JavaScript teaches you a skill that transfers everywhere. This lesson covers if statements, the operators that test conditions, and the three kinds of loop you will use most, with worked examples you can run in your browser console.

Making decisions with if

An if statement runs a block of code only when a condition is true: if (score >= 10) { console.log('Well done!'); }. The condition uses comparison operators: === means strictly equal, !== means not equal, > and < mean greater and less than, and >= and <= include equality. Note the triple equals: a single = assigns a value, a double == compares loosely and can surprise you, for example by treating the number 5 and the string '5' as equal, so this course always uses ===, which checks both value and type. You can chain decisions with else if and else, so a program can handle several cases in order, and the logical operators && (and), || (or) and ! (not) let you combine conditions, such as if (age >= 13 && hasPermission) { ... }. Keep conditions readable by storing them in well-named variables when they get long.

Loops: doing work repeatedly

A for loop repeats a block a known number of times, and its three parts are written in the header: for (let i = 0; i < 5; i++) { ... } starts i at 0, runs while i is less than 5, and adds 1 to i after each pass, so the block runs five times. A while loop repeats while a condition stays true, which suits jobs where you do not know in advance how many passes you need, such as reading input until the visitor types “stop”, but it needs a way for the condition to become false, or it will run forever and freeze the page. The most common loop in web development is the one that walks through an array: for (const lesson of lessons) { console.log(lesson); } runs once per item, with lesson set to each value in turn, and that pattern is how you build a list of lessons, a table of results or a row of cards from data. Choose the loop that matches the job, and always check that it can finish.

const marks = [72, 85, 64, 91];
let total = 0;
for (const mark of marks) {
  total = total + mark;
}
const average = total / marks.length;
if (average >= 70) {
  console.log('Pass, average ' + average);
} else {
  console.log('Keep practising, average ' + average);
}

Common mistakes and how to avoid them

Three mistakes cause most loop and decision bugs, and all three are easy to avoid once you know them. The first is the off-by-one error: an array with 4 items has indexes 0 to 3, so a loop written as i <= marks.length runs one time too many and reads an item that does not exist, giving undefined, while i < marks.length is correct. The second is using = where you meant ===, which assigns instead of comparing and is almost always a bug, so some developers write the value first, as in if (10 === score), which makes the mistake impossible. The third is the infinite loop, usually a while loop whose condition never becomes false, which freezes the browser tab; if that happens, close the tab, find the condition, and add a counter or a clear exit. When a loop misbehaves, add a console.log inside it to watch the values change, and the bug usually reveals itself within a few passes.

Putting decisions and loops together

Real programs combine decisions and loops constantly. A quiz app loops through its questions, and inside the loop it decides whether each answer is right, adding a point when it is. A to-do list loops through its tasks and decides which ones to show, hiding the completed ones when a filter is on. A form validator loops through its fields and decides which ones are empty, collecting the problems into a list. The pattern is always the same: a loop to visit everything, a decision to judge each item, and an action based on the result. Practise by writing a small program that takes a list of numbers, adds up only the ones above 50, and reports the count and the total, which uses everything in this lesson in about ten lines, and then try changing the threshold to a variable so the same code works for any cut-off.

Key Terms

Control flow
The order in which a program runs its instructions, changed by decisions and loops.
Condition
A test that is true or false, such as score >= 10, used by if statements and loops.
Comparison operator
An operator that compares two values, such as ===, !==, > and <.
for loop
A loop that repeats a known number of times, with a counter in its header.
while loop
A loop that repeats while a condition stays true.
Off-by-one error
A bug where a loop runs one time too many or too few, often from using <= instead of <.
Infinite loop
A loop whose condition never becomes false, so it runs forever and freezes the page.

Discussion Questions

  1. Why does this course insist on === instead of ==? Find an example where == gives a surprising answer.
  2. A while loop and a for loop can both repeat work. How do you decide which one to use?
  3. Why is it helpful to store a long condition in a well-named variable before using it in an if statement?

Practice Questions

  1. What is the difference between = and === in JavaScript?
  2. How many times does for (let i = 0; i < 5; i++) run its block?
  3. An array has 4 items. What are its indexes, and what happens if you read index 4?
  4. When would you use a while loop instead of a for loop?
  5. What does for (const lesson of lessons) do?
Show answers
  1. = assigns a value, === compares value and type. Writing score = 10 changes score, while score === 10 tests whether score is the number 10.
  2. Five times. i takes the values 0, 1, 2, 3 and 4, and the loop stops when i reaches 5.
  3. Its indexes are 0, 1, 2 and 3, and reading index 4 gives undefined. The last valid index is always one less than the length.
  4. When you do not know in advance how many times to repeat. A while loop runs until a condition becomes false, such as reading input until the visitor types “stop”.
  5. It runs once for each item in the lessons array. On each pass, lesson holds the next value, so you can work with every item in turn.
Keep reading to complete this lesson