Beginner · Strings, decisions and loops · topic 9 of 61 · 25 min
Loops: for, while, do…while, for…of and for…in
Explanation
Why loops?
Computers are good at doing the same thing many times without getting tired. A loop runs a block of code again and again. Each run is called an iteration. Without loops you would have to copy the same line a thousand times for a thousand orders.
The for loop: counting
A for loop has three parts inside the brackets, separated by semicolons: a start (let i = 0), a condition checked before every round (i < 5), and an update run after every round (i++).
for (let i = 1; i <= 5; i++) {
console.log('Table of 7:', 7 * i);
}while and do…while
while repeats as long as its condition is true. Use it when you do not know in advance how many rounds you need. do…while runs the body once BEFORE checking, so it always runs at least once.
let balance = 1000;
let months = 0;
while (balance > 0) {
balance -= 300;
months++;
}
console.log(months); // 4
let tries = 0;
do {
tries++;
} while (tries < 0);
console.log(tries); // 1 (the body ran once even though the condition was false)for…of: the items of an iterable
for…of gives you each VALUE of an array, a string, a Map or a Set, one by one. It is the clearest loop when you do not need the index.
const cart = ['rice', 'dal', 'ghee'];
for (const item of cart) {
console.log(item);
}
for (const ch of 'UPI') console.log(ch); // U, P, Ifor…in: the keys of an object
for…in gives you each property NAME (key) of an object. Do not use it on arrays: the keys come out as strings ('0', '1') and it can also visit inherited or extra properties. For arrays use for…of or a normal for.
const stock = { rice: 40, dal: 25 };
for (const key in stock) {
console.log(key, stock[key]); // rice 40, then dal 25
}break and continue
for (const n of [3, 8, -1, 5]) {
if (n < 0) break; // stop the whole loop
if (n % 2 === 0) continue; // skip even numbers
console.log(n);
}Labels let break leave an outer loop from inside an inner one (outer: for (...) { for (...) { break outer; } }). They are rarely needed; a function with return is usually clearer.
| Loop | Best for |
|---|---|
| for (let i = 0; i < n; i++) | Counting, or when you need the index |
| while (cond) | Repeat until something changes; unknown count |
| do { } while (cond) | Must run at least once (e.g. show a menu) |
| for (const x of list) | Each value of an array, string, Map, Set |
| for (const k in obj) | Each key of a plain object |
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Loops: for, while, do…while, for…of and for…in · 1/6
In this lesson you will repeat work with loops.
Prefer a video by a teacher? Find free videos on “javascript loops for while for of for in tutorial” on YouTube ↗
In real life: Retrying a failed SMS
OTP services sometimes fail to send an SMS. The server retries a few times before giving up. A while loop with a counter and a break when the send succeeds handles this cleanly. Here sendSms is simulated so that it succeeds on the third try.
let attempt = 0;
let sent = false;
while (attempt < 5 && !sent) {
attempt++;
sent = attempt === 3; // pretend the 3rd try works
}
console.log(sent ? `Sent on try ${attempt}` : 'Failed');Practice (0/3 done)
Write a function sumTo(n) that returns 1 + 2 + … + n using a for loop. sumTo(0) is 0.
Write a function countVowels(text) that uses for…of to count the vowels a, e, i, o, u (upper or lower case).
Write a function monthsToSave(target, perMonth) that returns how many months of saving perMonth it takes to reach at least target, using a while loop. If perMonth is 0 or less, return -1 (it would never finish).
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Loop patterns that solve real problemsStrings, decisions and loops · same module
- Decisions with if and elseStrings, decisions and loops · same module
- Loops: repeating workFrontend Web Development · JavaScript basics
- Loops: for, while, do-while and for-eachJava Programming (Core to Spring Boot) · Control flow and methods
- Loops: for, while, do-while and range-forC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Loops: for, while, do-while and foreachC# and .NET · Decisions, loops and methods
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
How many times does for (let i = 0; i < 3; i++) run its body?
Answer: 3
i takes the values 0, 1 and 2.
Which loop always runs its body at least once?
Answer: do…while
do…while checks the condition after the first run.
for (const k in ["a", "b"]) console.log(k); What is printed?
Answer: 0, 1 (as strings)
for…in gives keys, and array keys are the indexes as strings.
What does continue do?
Answer: Skips the rest of this round and starts the next
continue jumps to the next iteration; break ends the loop.
Which loop is best to visit every item of an array?Related
Answer: for...of
for...of gives you each item in turn, with no index to manage.
How do you leave an outer loop from inside an inner loop?Related
Answer: A labelled break, like break outer;
Labels let break target an outer loop.
Which loop always runs its body at least once?Related
Answer: do-while
do-while checks its condition after the body.
Which loop always runs its body at least once?Related
Answer: do-while
do-while checks the condition after the body.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “Strings, decisions and loops” before its exam: Loop patterns that solve real problems.
- Module 2 exam: Strings, decisions and loops · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functions and closures. 61 topics left in the course before the final exam.