JavaScript Loops: for, while, do…while, for…of and for…in with Examples

Loops repeat code: check every row in a table, retry a request until it succeeds, run the same test with ten sets of data. JavaScript has several loop types, and choosing the right one makes code shorter and avoids bugs such as skipping the last item or looping forever. In this lesson you will learn every loop, the difference between for...of and for...in, nested loops, and the important rule for using await inside loops.

Advertisement

📖 What You’ll Learn: the for loop and its three parts, while and do…while, for…of for arrays, strings and Maps, for…in for object keys, Array.forEach, Object.entries, nested loops, infinite loops and how to avoid them, off-by-one errors, choosing the right loop, and await inside loops.


🔁 What Is a Loop?

Definition: a loop runs a block of code repeatedly, either a fixed number of times or while a condition stays true. Each run of the block is called an iteration.

LoopBest for
forCounting: a known number of iterations, or when you need the index
whileRepeating until a condition changes (unknown number of iterations)
do...whileLike while, but the body must run at least once
for...ofValues of arrays, strings, Maps, Sets
for...inKeys (property names) of an object
array.forEach()Calling a function for each array item

🔢 The for Loop

A for loop has three parts in its parentheses, separated by semicolons:

📄 Syntax

for (initialisation; condition; update) {
  // body
}
  1. Initialisation runs once before the loop, usually let i = 0.
  2. Condition is checked before every iteration; the loop stops when it is falsy.
  3. Update runs after every iteration, usually i++.

📄 for.js

for (let i = 1; i <= 5; i++) {
  console.log(`Run ${i} of 5`);
}

const browsers = ["chromium", "firefox", "webkit"];
for (let i = 0; i < browsers.length; i++) {
  console.log(i, browsers[i]);
}

for (let i = 10; i > 0; i -= 3) {   // counting down in steps of 3
  console.log("countdown", i);
}

⌨️ Terminal

node for.js

🖥️ Output

Run 1 of 5
Run 2 of 5
Run 3 of 5
Run 4 of 5
Run 5 of 5
0 chromium
1 firefox
2 webkit
countdown 10
countdown 7
countdown 4
countdown 1

⚠️ Watch out: Off-by-one errors are the most common loop bug. Array indexes go from 0 to length - 1, so the condition is i < arr.length, not i <= arr.length. Using <= reads one item past the end, which is undefined.

📄 off-by-one.js

const items = ["pen", "book"];
for (let i = 0; i <= items.length; i++) {   // bug: <= instead of <
  console.log(i, items[i]);
}

⌨️ Terminal

node off-by-one.js

🖥️ Output

0 pen
1 book
2 undefined

⏳ The while Loop

A while loop checks its condition before each iteration and runs as long as it is truthy. Use it when you do not know in advance how many iterations you need.

📄 while.js

let attempt = 0;
let connected = false;

while (!connected && attempt < 5) {
  attempt++;
  connected = attempt === 3;          // pretend the 3rd attempt works
  console.log(`Attempt ${attempt}: ${connected ? "connected" : "failed"}`);
}
console.log(connected ? "Ready" : "Gave up after 5 attempts");

⌨️ Terminal

node while.js

🖥️ Output

Attempt 1: failed
Attempt 2: failed
Attempt 3: connected
Ready

⚠️ Watch out: If nothing inside the loop ever makes the condition false, you get an infinite loop and the program hangs. Always change something the condition depends on, and add a safety limit such as attempt < 5. Stop a hanging Node.js script with Ctrl+C.


Advertisement

🔂 The do…while Loop

do...while runs the body first and checks the condition afterwards, so the body always runs at least once.

📄 do-while.js

let page = 1;
const totalPages = 1;   // the API reports only one page

do {
  console.log(`Fetching page ${page}`);
  page++;
} while (page <= totalPages);

let count = 10;
while (count < 5) {
  console.log("while: never printed");
}
do {
  console.log("do...while: printed once even though 10 < 5 is false");
} while (count < 5);

⌨️ Terminal

node do-while.js

🖥️ Output

Fetching page 1
do...while: printed once even though 10 < 5 is false

📋 for…of: Loop Over Values

for...of loops over the values of an iterable: arrays, strings, Maps, Sets and more. It is the cleanest loop for arrays when you do not need the index.

📄 for-of.js

const tests = ["login", "search", "checkout"];
for (const test of tests) {
  console.log("running", test);
}

for (const ch of "QA!") {
  console.log(ch);
}

const scores = new Map([["asha", 91], ["ravi", 78]]);
for (const [name, score] of scores) {
  console.log(name, score);
}

for (const [index, test] of tests.entries()) {   // value and index
  console.log(index + 1, test);
}

⌨️ Terminal

node for-of.js

🖥️ Output

running login
running search
running checkout
Q
A
!
asha 91
ravi 78
1 login
2 search
3 checkout

💡 Tip: Use const in for...of when you do not reassign the loop variable. Each iteration gets a fresh binding, so const is allowed.


🗝️ for…in: Loop Over Object Keys

for...in loops over the keys (property names) of an object. Read the value with bracket notation obj[key].

📄 for-in.js

const config = { browser: "chromium", headless: true, retries: 2 };

for (const key in config) {
  console.log(`${key} = ${config[key]}`);
}

// Object.entries gives key and value together, and works with for...of
for (const [key, value] of Object.entries(config)) {
  console.log(key.padEnd(9), "->", value);
}

⌨️ Terminal

node for-in.js

🖥️ Output

browser = chromium
headless = true
retries = 2
browser   -> chromium
headless  -> true
retries   -> 2

⚠️ Watch out: Do not use for...in on arrays. It gives you the indexes as strings and also includes any extra properties added to the array. Use for...of, a classic for or forEach for arrays.

📄 for-in-array.js

const list = ["a", "b"];
list.note = "extra property";

for (const i in list) {
  console.log(i, typeof i);
}
for (const value of list) {
  console.log(value);
}

⌨️ Terminal

node for-in-array.js

🖥️ Output

0 string
1 string
note string
a
b
for...offor...in
Gives youValuesKeys (as strings)
Works onIterables: arrays, strings, Map, SetObjects (any object)
Use for arrays?YesNo
Plain objectsNo (TypeError: not iterable) — use Object.entries()Yes

🧾 Array.forEach

array.forEach(callback) calls a function once for every item, passing the item, its index and the array. It is common in existing code.

📄 foreach.js

const prices = [120, 80, 45];
let total = 0;

prices.forEach((price, index) => {
  console.log(`item ${index + 1}: ${price}`);
  total += price;
});
console.log("total", total);

⌨️ Terminal

node foreach.js

🖥️ Output

item 1: 120
item 2: 80
item 3: 45
total 245
  • You cannot stop forEach early with break; use for...of or some()/find() when you need to stop.
  • forEach does not wait for async callbacks (see the last section).
  • To build a new array from an existing one, map() and filter() are better choices (Module 6).

Advertisement

🪆 Nested Loops

A loop inside another loop runs the inner loop completely for every iteration of the outer loop. A common use is combining two lists, for example every browser with every viewport:

📄 nested.js

const browsers = ["chromium", "firefox"];
const viewports = ["mobile", "desktop"];

for (const browser of browsers) {
  for (const viewport of viewports) {
    console.log(`test on ${browser} / ${viewport}`);
  }
}

// A multiplication table: rows x columns
for (let r = 1; r <= 3; r++) {
  let row = "";
  for (let c = 1; c <= 4; c++) {
    row += String(r * c).padStart(4);
  }
  console.log(row);
}

⌨️ Terminal

node nested.js

🖥️ Output

test on chromium / mobile
test on chromium / desktop
test on firefox / mobile
test on firefox / desktop
   1   2   3   4
   2   4   6   8
   3   6   9  12

The total work is outer × inner iterations. Two lists of 1,000 items already means 1,000,000 iterations, so watch nested loops on large data.


⏱️ Loops and await (Important for Playwright)

Test code is full of await (you will learn promises and async/await in Module 10). The rule to remember now: await works inside for, for...of and while, but forEach does not wait.

📄 await-loop.js

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function main() {
  console.log("--- for...of waits for each step ---");
  for (const step of ["open", "login", "verify"]) {
    await sleep(10);
    console.log("done:", step);
  }
  console.log("all steps finished");

  console.log("--- forEach does NOT wait ---");
  ["open", "login", "verify"].forEach(async (step) => {
    await sleep(10);
    console.log("done:", step);
  });
  console.log("forEach returned (steps still running!)");
}

main();

⌨️ Terminal

node await-loop.js

🖥️ Output

--- for...of waits for each step ---
done: open
done: login
done: verify
all steps finished
--- forEach does NOT wait ---
forEach returned (steps still running!)
done: open
done: login
done: verify

⚠️ Watch out: In a Playwright test, items.forEach(async (item) => { await page.click(...) }) lets the test finish before the clicks happen, causing random failures. Use for (const item of items) { await ... } instead.


🧪 Tester Scenario: Data-Driven Checks

Running the same check with many inputs is called data-driven testing. A loop over a table of cases keeps it short:

📄 data-driven.js

function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

const cases = [
  { input: "qa@sqatools.in", expected: true },
  { input: "first.last@company.co.uk", expected: true },
  { input: "missing-at.com", expected: false },
  { input: "spaces in@mail.com", expected: false },
  { input: "", expected: false },
];

let failures = 0;
for (const { input, expected } of cases) {
  const actual = isValidEmail(input);
  const ok = actual === expected;
  if (!ok) failures++;
  console.log(`${ok ? "PASS" : "FAIL"}  ${JSON.stringify(input).padEnd(28)} expected ${expected}, got ${actual}`);
}
console.log(`${cases.length - failures}/${cases.length} passed`);

⌨️ Terminal

node data-driven.js

🖥️ Output

PASS  "qa@sqatools.in"             expected true, got true
PASS  "first.last@company.co.uk"   expected true, got true
PASS  "missing-at.com"             expected false, got false
PASS  "spaces in@mail.com"         expected false, got false
PASS  ""                           expected false, got false
5/5 passed

Playwright supports the same idea directly: put a test() call inside a for...of loop over your cases, and each case appears as its own test in the report.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Print the even numbers from 2 to 20 with a for loop, all on one line.

Show answer

📄 practice1.js

let line = "";
for (let n = 2; n <= 20; n += 2) {
  line += n + " ";
}
console.log(line.trim());

🖥️ Output

2 4 6 8 10 12 14 16 18 20

Q2. Calculate the sum and the average of [12, 7, 30, 5, 16] with a for...of loop.

Show answer

📄 practice2.js

const values = [12, 7, 30, 5, 16];
let sum = 0;
for (const v of values) {
  sum += v;
}
console.log("sum", sum, "average", sum / values.length);

🖥️ Output

sum 70 average 14

Q3. Reverse the string "playwright" with a loop (without reverse()).

Show answer

📄 practice3.js

const word = "playwright";
let reversed = "";
for (let i = word.length - 1; i >= 0; i--) {
  reversed += word[i];
}
console.log(reversed);

🖥️ Output

thgirwyalp

Q4. Count how many times each status appears in ["pass", "fail", "pass", "skip", "pass"], storing the counts in an object.

Show answer

📄 practice4.js

const statuses = ["pass", "fail", "pass", "skip", "pass"];
const counts = {};
for (const s of statuses) {
  counts[s] = (counts[s] ?? 0) + 1;
}
console.log(counts);
for (const key in counts) {
  console.log(`${key}: ${counts[key]}`);
}

🖥️ Output

{ pass: 3, fail: 1, skip: 1 }
pass: 3
fail: 1
skip: 1

Q5. Use a while loop to find the first power of 2 that is greater than 1000.

Show answer

📄 practice5.js

let power = 1;
let exponent = 0;
while (power <= 1000) {
  power *= 2;
  exponent++;
}
console.log(`2^${exponent} = ${power}`);

🖥️ Output

2^10 = 1024

Q6. Print a right-angled triangle of * with 5 rows using nested loops.

Show answer

📄 practice6.js

for (let row = 1; row <= 5; row++) {
  let line = "";
  for (let col = 1; col <= row; col++) {
    line += "*";
  }
  console.log(line);
}

🖥️ Output

*
**
***
****
*****

A shorter alternative for each line is "*".repeat(row).


🧠 MCQ Quiz: Loops

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. How many times does for (let i = 0; i < 5; i++) run its body?
  2. Which loop always runs its body at least once?
  3. What does for (const x of ["a", "b"]) give you in x?
  4. What does for (const k in { a: 1, b: 2 }) give you in k?
  5. Why should you avoid for…in on arrays?
  6. What happens with for (const x of { a: 1 })?
  7. With arr = ["x", "y"], what is printed last by for (let i = 0; i <= arr.length; i++) console.log(arr[i])?
  8. Which loop does not wait for await inside its callback?
  9. How many times does the inner body run?
    for (let i = 0; i < 3; i++)
      for (let j = 0; j < 4; j++)
        count++;
  10. How do you get both key and value when looping over an object with for…of?

💼 Interview Questions and Answers

Q1. What is the difference between for…of and for…in?

for...of iterates the values of iterables (arrays, strings, Maps, Sets, generators) using the iterator protocol. for...in iterates the enumerable keys of any object, including inherited ones, as strings. Use for...of for arrays and for...in (or better Object.keys/Object.entries) for plain objects.

Q2. What is the difference between forEach and for…of?

forEach is an array method that calls a callback for each item; you cannot break out of it, return only ends the current callback, and it does not await async callbacks. for...of is a language loop: it supports break, continue and await, and works on any iterable, not only arrays. In async test code, prefer for...of.

Q3. A Playwright test loops over menu links with forEach and clicks each one, but it passes even when links are broken. Why?

The callback is async, and forEach ignores the promises it returns. The test function reaches its end, so the test is reported as passed, while the clicks and assertions run (and may fail) afterwards or are cancelled when the page closes. Fix: for (const link of links) { await link.click(); await expect(...)... }. Use Promise.all only when the steps can safely run in parallel.

Q4. How do you avoid infinite loops in retry logic?

Always bound the loop: a maximum attempt count or a deadline (Date.now() < start + timeout), update the variables the condition depends on inside the loop, and add a delay between attempts. After the loop, fail with a clear error that includes the last result. Built-in waiting tools (Playwright’s auto-waiting, expect.poll, toPass) handle this for you and are preferred in tests.

📄 bounded-retry.js

function retry(action, maxAttempts = 3) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const ok = action(attempt);
    console.log(`attempt ${attempt}: ${ok ? "ok" : "failed"}`);
    if (ok) return attempt;
  }
  throw new Error(`Failed after ${maxAttempts} attempts`);
}

retry((n) => n === 2);
try {
  retry(() => false);
} catch (e) {
  console.log(e.message);
}

⌨️ Terminal

node bounded-retry.js

🖥️ Output

attempt 1: failed
attempt 2: ok
attempt 1: failed
attempt 2: failed
attempt 3: failed
Failed after 3 attempts

Q5. What is an off-by-one error? Give an example.

A loop that runs one time too many or too few, usually because of <= versus < or starting at 1 instead of 0. Example: for (let i = 0; i <= arr.length; i++) reads arr[arr.length], which is undefined. Iterating values with for...of avoids index arithmetic entirely, and boundary tests (empty array, one item, last item) catch these bugs.


Advertisement

❓ Frequently Asked Questions

🤔 Which loop is fastest in JavaScript?

For normal data sizes the differences are tiny. Choose for readability: for...of for arrays, for when you need the index or a custom step, while for unknown iteration counts.

🤔 How do I loop through an object in JavaScript?

Use for (const [key, value] of Object.entries(obj)), or for...in for the keys. Object.keys() and Object.values() give arrays of keys or values.

🤔 How do I stop a loop early?

Use break to leave the loop or continue to skip to the next iteration. These are covered in the next lesson. They do not work in forEach.

🤔 Can I use await inside a for loop?

Yes, in an async function, await works in for, for...of, while and do...while, and each iteration waits. It does not work as expected inside forEach.


🏁 Summary

  • for counts with initialisation, condition and update; use i < arr.length to avoid off-by-one errors.
  • while repeats while a condition is true; do...while always runs at least once; always make sure the loop can end.
  • for...of gives values of arrays, strings, Maps and Sets; for...in gives object keys and should not be used on arrays.
  • forEach cannot break and does not wait for await; use for...of in async test code.
  • Loops over tables of inputs and expected results are the basis of data-driven testing.

Next, continue with Lesson 16: break, continue and Labels. For extra practice, solve the JavaScript loop practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in