JavaScriptLesson 5 of 10Jump to practice
Loops
Repeat code with for, for...of and while, without copying it over and over.
A loop runs the same code again and again. Instead of writing ten console.log lines, you write one and loop ten times.
The for loop
for (let i = 0; i < 5; i++) {
// runs 5 times, with i = 0, 1, 2, 3, 4
}
It has three parts, separated by semicolons:
- Start:
let i = 0creates a counter. - Keep going while:
i < 5is checked before every round. - After each round:
i++adds one to the counter.
<script>
const number = 7;
for (let i = 1; i <= 10; i++) {
console.log(number + " x " + i + " = " + number * i);
}
</script>for…of: every item in a list
When you have an array, for...of gives you each item in turn. No counter needed.
<ul id="list"></ul>
<script>
const cities = ["Chicago", "Houston", "Seattle", "Denver"];
const list = document.getElementById("list");
for (const city of cities) {
const item = document.createElement("li");
item.textContent = city;
list.append(item);
}
console.log("Added " + cities.length + " cities");
</script>This is how real sites turn data into HTML: loop over the data, create an element for each item. You’ll see createElement again in the DOM lesson.
while: until something changes
A while loop keeps going as long as its condition is true. Use it when you don’t know in advance how many rounds you need.
<script>
let savings = 0;
let weeks = 0;
while (savings < 1000) {
savings += 150;
weeks++;
}
console.log("It takes " + weeks + " weeks to save $" + savings + ".");
</script>break and continue
breakstops the loop completely.continueskips the rest of this round and moves to the next.
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue; // skip even numbers
if (i > 7) break; // stop after 7
console.log(i); // 1, 3, 5, 7
}Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Start a counting loop.
(let i = 0; i < 3; i++) { console.log(i); }Exercise 2Solved
Loop over every item in the array.
const fruits = ["apple", "grape", "banana"]; for (const fruit fruits) { console.log(fruit); }Exercise 3Solved
Count from 1 to 5, including 5.
for (let i = 1; i 5; i++) { console.log(i); }
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.
