Lesson 3 of 11JavaScript
JavaScript · Lesson 3 · 30 minutes
Loops
What you'll learn
- Count with
for - Repeat with
whileas long as something holds - Add up results in a loop
The for loop
The classic for loop has three parts in its brackets – start, condition, step:
for (let i = 1; i <= 5; i++) {
console.log("Round", i);
}let i = 1– the counter starts at 1i <= 5– carry on as long as this holdsi++– increase by 1 after every round (short fori = i + 1)
Python comparison:
for i in range(1, 6):in Python is exactly this loop.
Adding up
let total = 0;
for (let i = 1; i <= 3; i++) {
total += i; // short for total = total + i
console.log("i =", i, "total =", total);
}The while loop
while repeats as long as a condition is true – handy when you don’t know beforehand how often:
let money = 100;
let years = 0;
while (money < 200) {
money = money * 1.1;
years++;
}
console.log(`After ${years} years you have £${Math.round(money)}.`);Careful: if the condition never becomes false, the loop runs forever. You can then stop it with the Stop button.
Quick check
What does this program print?
let text = "";
for (let i = 3; i > 0; i--) {
text += i;
}
console.log(text);Your task
Your turn
Write the function sumUpTo(n) that adds up all numbers from 1 to n and returns the result – sumUpTo(4) gives 1 + 2 + 3 + 4 = 10. Use a loop for it.
function sumUpTo(n) {
let total = 0;
// Add up here with a loop
return total;
}
console.log(sumUpTo(4));- Something to think about
A
forloop from 1 to n:for(leti=1; i<=n; i++) { total+=i; } - Gap code – fill in the ___
function sumUpTo(n) { let total = 0; for (___) { total += ___; } return total; } console.log(sumUpTo(4));
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
function sumUpTo(n) {
let total = 0;
for (let i = 1; i <= n; i++) {
total += i;
}
return total;
}
console.log(sumUpTo(4));