Introduction & Syntax
Loops · Study material
Loops run code again and again – over a range of numbers, the items of an array, the characters of a string or the keys of an object. JavaScript has five loop statements and several array methods that loop for you, and interviews test the differences: for…of vs for…in, why forEach cannot break, what do…while guarantees, how labels work, and the bugs that come from changing an array while looping over it. This topic covers all of them. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
for, while and do…while
| Loop | Use it when | Runs at least once? |
|---|---|---|
for (init; condition; update) | you know how many times, or need the index | no |
while (condition) | you loop until something changes | no |
do { } while (condition); | the body must run before the first test (menus, retries) | yes |
for (const v of iterable) | you need the values of an array, string, Map, Set | no |
for (const k in object) | you need the keys of a plain object | no |
// for: initialise; test before each pass; update after each pass
const squares = [];
for (let i = 1; i <= 5; i++) squares.push(i * i);
console.log("for:", squares.join(" "));
// while: test first – may run zero times
let n = 100, steps = 0;
while (n > 1) { n = Math.floor(n / 2); steps++; }
console.log("while: halved", steps, "times");
// do…while: body first, test after – always runs at least once
let tries = 0;
do { tries++; } while (false);
console.log("do…while ran", tries, "time");
for: 1 4 9 16 25 while: halved 6 times do…while ran 1 time
for…of vs for…in
for…of walks the values of any iterable (arrays, strings, Maps, Sets, arguments, NodeLists). Plain objects are not iterable, so for…of on them throws a TypeError. for…in walks the enumerable keys of an object – as strings – including keys inherited from its prototype. Do not use for…in on arrays: the indexes are strings and inherited or extra properties appear too.
const fruits = ["mango", "apple"];
for (const f of fruits) console.log("of:", f); // for…of → VALUES of an iterable
for (const k in fruits) console.log("in:", k, typeof k); // for…in → KEYS, always strings
const student = { name: "Asha", marks: 91 };
for (const key in student) console.log(key, "=", student[key]); // objects: use for…in or Object.entries
for (const [key, value] of Object.entries(student)) console.log(`${key} → ${value}`);
of: mango of: apple in: 0 string in: 1 string name = Asha marks = 91 name → Asha marks → 91
break, continue and labels
break leaves the loop; continue skips the rest of the current pass and goes to the next one. In nested loops both affect only the innermost loop – unless you put a label before the outer loop and write break label; or continue label;.
// continue skips to the next pass; break leaves the loop
const picked = [];
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue; // skip even numbers
if (i > 7) break; // stop completely after 7
picked.push(i);
}
console.log(picked);
// A label lets break leave an OUTER loop from inside an inner one
outer: for (let r = 1; r <= 3; r++) {
for (let c = 1; c <= 3; c++) {
if (r * c === 4) {
console.log(`found 4 at row ${r}, col ${c}`);
break outer;
}
}
}
[ 1, 3, 5, 7 ] found 4 at row 2, col 2
forEach cannot break
array.forEach(callback) calls the callback for every element. break and continue are not allowed inside the callback (a SyntaxError), and return only ends the current call. To stop early use for…of with break, or a method that stops by itself: some(), every(), find(), findIndex().
const marks = [45, 72, 30, 88];
// return inside forEach only ends THIS callback call – the loop keeps going
marks.forEach((m) => {
if (m < 40) return;
console.log("pass:", m);
});
// To stop early, use for…of with break, or some()/find()
for (const m of marks) {
if (m < 40) { console.log("first fail:", m); break; }
}
console.log("any fail?", marks.some((m) => m < 40));
pass: 45 pass: 72 pass: 88 first fail: 30 any fail? true
Iterables
Strings iterate by character (by code point, so emoji stay whole), Maps by [key, value] pairs, Sets by value. array.entries(), Object.entries(obj) and destructuring give you index/key and value together.
// for…of works on anything iterable: strings, Maps, Sets, array.entries() …
for (const ch of "JS") console.log(ch);
const stock = new Map([["pen", 40], ["book", 12]]);
for (const [item, qty] of stock) console.log(item, qty);
for (const [index, value] of ["a", "b"].entries()) console.log(index, value);
const unique = new Set([3, 1, 3, 2]);
let total = 0;
for (const v of unique) total += v; // duplicates were removed by the Set
console.log("total of unique:", total);
J S pen 40 book 12 0 a 1 b total of unique: 6
Order of object keys
for…in, Object.keys and JSON.stringify list integer-like keys first, in ascending numeric order, then the other string keys in the order they were added. Output questions use this rule often.
// Integer-like keys come first, in ascending order; other string keys follow in insertion order
const obj = { b: 1, 10: "ten", a: 2, 2: "two" };
const keys = [];
for (const k in obj) keys.push(k);
console.log(keys.join(" "));
console.log(Object.keys(obj).join(" ")); // same order
2 10 b a 2 10 b a
Common mistakes
- Off-by-one –
i <= arr.lengthreads one element past the end (undefined). - for…in on arrays – keys are strings ("0" + 1 is "01") and extra properties appear.
- for…of on a plain object – TypeError: object is not iterable; use Object.entries.
- break inside forEach – a SyntaxError; return does not stop the loop either.
- splice while looping forward – the next element shifts into the current index and is skipped.
- Forgetting to update the condition – an infinite while loop.
- var in loops with callbacks – every callback sees the last value (use let).
Key points to remember
- while tests first; do…while runs the body at least once.
- for…of gives values of iterables; for…in gives string keys (own and inherited).
- Plain objects are not iterable – loop over Object.keys / values / entries.
- break and continue affect the innermost loop unless a label is used.
- forEach cannot be stopped; use for…of, some, every or find.
- Integer keys are listed first in ascending order.
- Loop backwards (or filter) when removing items.
Frequently asked questions
Which loop is fastest?
In modern engines the differences are tiny for normal data. Choose the clearest loop: for…of for values, a classic for when you need the index or a custom step, array methods (map, filter, reduce) when you build a new value.
How do I loop over an object?
for (const [key, value] of Object.entries(obj)) is the clearest. for…in also works but includes inherited enumerable keys.
Can I use await inside loops?
Yes, inside for, for…of and while in an async function – each iteration waits. forEach does not wait for async callbacks. The Async/Await topic covers this.
Where can I learn more?
Read JavaScript Loops in the JavaScript tutorial, then practise with the exercises below.