Skip to content

Beginner · Strings, decisions and loops · topic 9 of 61 · 25 min

Loops: for, while, do…while, for…of and for…in

Explanation

A loop repeats code. Use for when you count, while when you repeat until something changes, for…of to walk through the items of an array or string, and for…in to walk through the keys of an object. break leaves a loop early and continue skips to the next round.

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++).

javascript
for (let i = 1; i <= 5; i++) {
  console.log('Table of 7:', 7 * i);
}
Prints 7, 14, 21, 28, 35, one per line.

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.

javascript
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)
Careful: An infinite loop never stops and freezes the program or browser tab. It usually happens when the variable in the condition never changes: while (i < 10) { console.log(i); } without i++. Always check that each round moves the loop toward its end.

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.

javascript
const cart = ['rice', 'dal', 'ghee'];
for (const item of cart) {
  console.log(item);
}
for (const ch of 'UPI') console.log(ch); // U, P, I

for…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.

javascript
const stock = { rice: 40, dal: 25 };
for (const key in stock) {
  console.log(key, stock[key]); // rice 40, then dal 25
}

break and continue

javascript
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);
}
Prints only 3: 8 is skipped by continue, and the loop stops at -1, so 5 is never reached.

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.

LoopBest 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
Tip: Declare the loop variable with let in a for loop and with const in for…of and for…in. Never use var in loops (module 3 shows the bug it causes with closures).

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

Loops

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.

javascript
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');
Prints Sent on try 3.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function sumTo(n) that returns 1 + 2 + … + n using a for loop. sumTo(0) is 0.

Task 2 · Code · Javascript

Write a function countVowels(text) that uses for…of to count the vowels a, e, i, o, u (upper or lower case).

Task 3 · Code · Javascript

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

Question 1

1.How many times does for (let i = 0; i < 3; i++) run its body?

Question 2

2.Which loop always runs its body at least once?

Question 3

3.for (const k in ["a", "b"]) console.log(k); What is printed?

Question 4

4.What does continue do?

Read more (free)

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.

From Loops: repeating work

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.

From Loops: for, while, do-while and for-each

Which loop always runs its body at least once?Related

Answer: do-while

do-while checks its condition after the body.

From Loops: for, while, do-while and range-for

Which loop always runs its body at least once?Related

Answer: do-while

do-while checks the condition after the body.

From Loops: for, while, do-while and foreach

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. 1 more topic in “Strings, decisions and loops” before its exam: Loop patterns that solve real problems.
  2. Module 2 exam: Strings, decisions and loops · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functions and closures. 61 topics left in the course before the final exam.

← Previous: switch, the ternary operator and lookup tables