for and for...of
Looping over many items without repeating yourself.
Step 1
The idea
Imagine you have 5 test cases and you need to run them all. You could write:
runTest("login");
runTest("checkout");
runTest("search");
runTest("logout");
runTest("profile");But what if you had 100? A loop does repetitive work automatically — you write the instruction once and JavaScript repeats it as many times as needed.
Two loops cover almost every case you'll encounter: for (when you know the count) and for...of (when you have a list).
Step 2
See it run
Test 1 of 5
Test 2 of 5
Test 3 of 5
Test 4 of 5
Test 5 of 5
---
Running: login
Running: checkout
Running: search
Running: logout
Running: profile// for loop — when you know the count
for (let i = 1; i <= 5; i++) {
console.log(`Test ${i} of 5`);
}
console.log("---");
// for...of loop — when you have a list (array)
const testCases = ["login", "checkout", "search", "logout", "profile"];
for (const testCase of testCases) {
console.log(`Running: ${testCase}`);
}$ node loops.jsThe for loop has three parts: start (let i = 1), condition (i <= 5), increment (i++). The loop runs while the condition is true.
Step 3
Now you try
Copy the loops file. Add a new array called urls with three website URLs, then use a for...of loop to print: Checking: https://example.com for each one.
Step 4
Why a tester cares
Loops let you process any amount of data with the same few lines of code. Here's a simple marks processor — the kind of thing a school system might run nightly:
const students = [
{ name: "Priya", marks: [85, 90, 78, 92] },
{ name: "Rahul", marks: [60, 55, 70, 65] },
{ name: "Anita", marks: [95, 98, 92, 97] },
];
for (const student of students) {
let total = 0;
for (const mark of student.marks) {
total += mark;
}
const average = total / student.marks.length;
const status = average >= 70 ? "PASS" : "FAIL";
console.log(`${student.name}: avg ${average.toFixed(1)} — ${status}`);
}$ node marks.jsPriya: avg 86.3 — PASS
Rahul: avg 62.5 — PASS
Anita: avg 95.5 — PASSTwo nested loops, pure JavaScript, zero repetition. Add 100 more students to the array and the exact same code handles them all.
Recap
- 1for (let i = 0; i < n; i++) — use when you need a counter or know the number of times.
- 2for (const item of array) — use when you have a list and want each item in turn.
- 3Both loops are essential for data-driven testing in Playwright.