Beginner · JavaScript basics · topic 21 of 64 · 25 min
Loops: repeating work
Explanation
Why loops?
Imagine printing a multiplication table, adding 50 prices or checking 1,000 roll numbers. Writing each line by hand is slow and error-prone. A loop does the repeating for you.
The for loop
for (let i = 1; i <= 5; i++) {
console.log(`7 x ${i} = ${7 * i}`);
}
// 7 x 1 = 7 ... 7 x 5 = 35- let i = 1 runs once at the start.
- i <= 5 is checked before every round; when it is false, the loop stops.
- The body runs.
- i++ runs after each round, then back to step 2.
for...of: every item
const prices = [120, 45, 60];
let total = 0;
for (const price of prices) {
total += price; // same as total = total + price
}
console.log(total); // 225
for (const letter of 'UPI') {
console.log(letter); // U, P, I
}The while loop
while repeats as long as its condition is true. Use it when you do not know in advance how many rounds you need, for example "keep doubling the savings until they cross 1 lakh".
let savings = 1000;
let months = 0;
while (savings < 2000) {
savings = savings * 1.1;
months++;
}
console.log(months); // 8break and continue
break stops the loop at once (for example, when you have found what you were looking for). continue skips the rest of this round and moves to the next one (for example, to skip empty entries).
Watch the lesson
Loops: repeating work · 1/6
Loops repeat work, so you write the steps once and run them many times.
Prefer a video by a teacher? Find free videos on “javascript loops for while for of tutorial beginners” on YouTube ↗
In real life: Totalling a kirana bill
A shop billing page keeps the prices of scanned items in a list. A for...of loop adds each price to a running total, a counter counts items above 500 rupees for a special discount, and a break stops the loop early if an item has no price, so the cashier can fix it.
Practice (0/3 done)
Write a function sumTo(n) that uses a loop to add all whole numbers from 1 to n. sumTo(4) is 1 + 2 + 3 + 4 = 10.
Write a function countAbove(prices, limit) that returns how many prices in the list are greater than limit. countAbove([100, 600, 750, 20], 500) is 2.
Write a function table(n) that returns an array of the first 10 multiples of n: table(3) returns [3, 6, 9, ..., 30].
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.