CoursePart 1 — JavaScript for PlaywrightLesson 1.9
Lesson 1.9Part 1 — JavaScript for Playwright

for and for...of

Looping over many items without repeating yourself.

Lesson 1.9of 24
Next

Step 1

The idea

01

Imagine you have 5 test cases and you need to run them all. You could write:

js
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

02
Output
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
loops.js
// 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}`);
}
Terminal
$ node loops.js

The 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

03

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.

💡Tip
In Playwright, you'll loop through a list of URLs to visit them all or a list of items to verify each one. The pattern is identical to what you just wrote.

Step 4

Why a tester cares

04

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:

marks.js
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}`);
}
Terminal
$ node marks.js
Output
Priya: avg 86.3 — PASS
Rahul: avg 62.5 — PASS
Anita: avg 95.5 — PASS

Two nested loops, pure JavaScript, zero repetition. Add 100 more students to the array and the exact same code handles them all.

Recap

3 key points
  • 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.