JavaScript · Unit 2: Decisions, functions and loops · Lesson 4 of 6
for loops
A loop repeats code.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
A loop repeats code. A for loop has three parts in its parentheses: a start (let i = 0), a condition checked before each round (i < 5) and a step run after each round (i++).
i++ adds 1 to i. The loop stops as soon as the condition is false, so for (let i = 0; i < 3; i++) runs with i = 0, 1 and 2.
Loops often build up a result, like adding numbers into a total that starts at 0.
Worked example
JavaScript
for (let i = 1; i <= 3; i++) {
console.log("Round", i);
}
let total = 0;
for (let n = 1; n <= 4; n++) {
total = total + n;
}
console.log(total);
It prints
Round 1
Round 2
Round 3
10
Key terms
- for loop
- Repeats code with a start, a condition and a step. for...of visits each item of an array.
Practise it in Code Academy
It has 4 exercises (predict the output, fill in the blank, fix the broken code and write code from a prompt) and takes about 8 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.