Learn / Lesson 6 of 10
Decisions and loops
Make your code choose what to do with if, and repeat steps with loops.
Words on this page, in plain English (9)Open if any word is new to you
- Variable
- A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
- Boolean (true or false)
- A value that can only be
trueorfalse. Like a light switch: on or off. - Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- Index (position)
- Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
- If (a decision)
- Runs some code only when something is true. Like: if it's raining, take an umbrella.
- Loop
- Code that repeats. A
forloop repeats once per item or a set number of times; awhileloop repeats as long as something stays true. - Return
- How a function hands back its answer. As soon as
returnruns, the function stops. - console.log
- Prints something so you can see it. The easiest way to find out what your code is really doing.
- Big O
- A way to say how much slower code gets as the input grows. It's about the trend, not exact seconds.
Making decisions with if
if runs some code only when a condition is true. else runs when it isn't:
Try it: if and else
const temperature = 28;
if (temperature > 25) {
console.log("Warm: wear shorts.");
} else {
console.log("Cool: bring a jacket.");
}Press Run to see the output. You can change the code first.
Change the temperature and run it again. For more than two choices, chain else if. The first condition that's true wins, and the rest are skipped:
Try it: several choices
const score = 72;
if (score >= 90) {
console.log("A");
} else if (score >= 70) {
console.log("B");
} else if (score >= 50) {
console.log("C");
} else {
console.log("Try again");
}Press Run to see the output. You can change the code first.
The code inside { } is called a block. Indenting it (moving it right) doesn't change what it does, but it makes it much easier to see what belongs to what.
Repeating with for
A for loop repeats a block a set number of times. It has three parts, separated by semicolons:
for (let i = 0; i < 5; i++) { // runs 5 times, with i = 0, 1, 2, 3, 4}let i = 0: start a counter at 0.i < 5: keep going while this is true.i++: after each round, add 1 toi(i++is short fori = i + 1).
Try it: counting
for (let i = 0; i < 5; i++) {
console.log("Round", i);
}Press Run to see the output. You can change the code first.
This shape is perfect for going through an array by position, from 0 to length - 1:
Try it: positions and values
const fruits = ["apple", "pear", "plum"];
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]);
}Press Run to see the output. You can change the code first.
When you only need the values, for...of is simpler. When you need positions too (to compare neighbours, or to return where something is), use the counting for.
Repeating with while
A while loop repeats as long as a condition stays true. Use it when you don't know in advance how many rounds it will take:
Try it: halving
let n = 100;
let steps = 0;
while (n > 1) {
n = Math.floor(n / 2);
steps++;
}
console.log("Took", steps, "halvings");Press Run to see the output. You can change the code first.
Careful: if the condition never becomes false, the loop never ends. On this site the code is stopped after 3 seconds; in a real program it freezes. Every loop needs something inside that moves it towards finishing.
break and continue
breakleaves the loop straight away.continueskips the rest of this round and goes on to the next.
Try it: break and continue
const nums = [3, -1, 4, 0, 5, 9];
for (const n of nums) {
if (n < 0) continue; // skip negatives
if (n === 0) break; // stop completely at zero
console.log(n);
}Press Run to see the output. You can change the code first.
Loops inside loops
A loop can sit inside another. The inner loop runs completely, for every round of the outer loop:
Try it: every pair
const letters = ["a", "b", "c"];
let pairs = 0;
for (let i = 0; i < letters.length; i++) {
for (let j = i + 1; j < letters.length; j++) {
console.log(letters[i] + letters[j]);
pairs++;
}
}
console.log(pairs, "pairs");Press Run to see the output. You can change the code first.
Notice how quickly the work grows: 3 items make 3 pairs, but 1,000 items make about 500,000. Keeping an eye on loops inside loops is the start of thinking about speed, which the Big O lesson is all about.
Your turn
Go through the numbers 1 to 20. For each one, show "fizz" if it divides by 3, "buzz" if it divides by 5, "fizzbuzz" if it divides by both, and the number itself otherwise. (Hint: check "both" first, and remember %.)
Your turn
for (let n = 1; n <= 20; n++) {
// your if / else if / else here
}Press Run to see the output. You can change the code first.
What you learned
if,else ifandelsechoose what runs.for (let i = 0; i < n; i++)counts;for...ofvisits values;whilerepeats until a condition is false.breakstops a loop;continueskips to the next round.- Loops inside loops multiply the work.