The Testing Academy · Class Notes Friday, 16 October (IST)
Live class · study guide

The three JavaScript loops: the for loop's init, condition and update, loop boundaries and infinite loops, while and break, do...while for retries, and five loop output questions

The three loops JavaScript has, and when to use each: for when you know the count, while when a condition decides, do...while when the body must run at least once. Then the for loop's three parts, init, condition and update, and the edges interviewers test: < or <=, a loop that never runs, an infinite loop, break, and five output questions. Files 63 to 77, pushed to the batch repo.

By Pramod Dutta, The Testing Academy. Study notes from the ninth class of Playwright 4x, built from the session recording, the batch repository, which received files 63 to 77 and three cheat-sheet images near the end of class (commit "feat: add chapters 09-11 on loops"), and the Eraser notes deck, which holds the five quiz questions. Every file was run with Node 22, the commented-out ones switched on, and so were the quiz questions; the output shown is what each one prints.

01

What this class covered

  • Loops: doing a task many times, and the three loops JavaScript has
  • Printing 1 to 10 by hand, and why that does not scale
  • The for loop: init, condition and update, and why i++ or ++i makes no difference
  • Loop boundaries: any counter name, < or <=, a loop that never runs, and one that never stops
  • if inside a loop: the gift question
  • The while loop: the same three parts, spread out
  • while (true) and break
  • do...while: the loop that runs at least once, for retries
  • while or do...while: why while is called an entry loop
  • Nested loops, and the for...of, for...in and forEach loops still to come
  • Five loop output questions
  • Tasks: the triangle classifier, Sunday's test and the Claude 101 certificate
02

Three loops, and when to use each

A loop repeats a task. From the class notes: a task that you want to do multiple times, or a simple task that you want repeated. JavaScript has three loops, for, while and do...while, and for, while and do are all keywords.

The class's way to tell them apart:

  • for: you have a full list of 50 accounts in front of you. You know the count, and you go through them one by one, top to bottom. Use for when you know how many times the loop must run.
  • while: you keep checking whether it is done, and stop the moment it is. You do not know in advance how many checks there will be. Use while when a condition decides.
  • do...while: you knock at least once, no matter what. It is the classic loop for retry logic: use it when the action must run at least once.
Two panels. Left, titled for, with the sublabel You know the count: a clipboard holds a fixed list of rows with a visible end; the top rows carry terracotta ticks and a pencil rests at the next one. Right, titled while, with the sublabel Until it is done: status boards with a dial a quarter, a half and three quarters full, and in front a board whose dial is full, with a terracotta tick beside a magnifying glass.
for when you know how many there are; while when you keep checking until the job is done, without knowing how many checks it will take.
THREE LOOPS, AND WHEN EACH ONE CHECKS ITS CONDITION KNOWN COUNT for (I; C; U) you know how many times: 50 accounts, top to bottom check C run body 0 runs if C starts false CONDITION DECIDES while (C) { ... } keep checking until done; the count is not known check C run body 0 runs if C starts false AT LEAST ONCE do { ... } while (C); runs first, checks after: retry a flaky action run body check C 1 run even if C starts false for and while check before the body, so they can run 0 times; do...while runs once, then checks.
The class's rule of thumb. for and while check before the body; do...while checks after it, which is what makes it the loop for retries.

The class notes call while the for loop's sister, and do...while its big sister.

03

Why loops: printing 1 to 10

To print 1 to 10 you could write ten console.log lines. The first file of chapter 09 starts that way, then skips from 5 to 10:

JavaScript
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
console.log("...");
console.log(10);
Text
1
2
3
4
5
...
10

That is not the way to do it. A loop does the same work in three lines, whether you need 10 values or 10,000.

04

The for loop: init, condition and update

A for loop repeats a block of code. Its header holds three parts, separated by semicolons, which the class remembers as ICU:

  • I, init: let i = 0. It runs once, before anything else.
  • C, condition: i < 10. It is checked before every pass, and when it is false, the loop ends.
  • U, update: i++ or ++i. It runs after every pass.

One habit from Java to drop: JavaScript has no int, so the counter is always declared with let. The class's file, with the long form left in comments:

JavaScript
// For Loop
// Help you to repeat a block of code.

// ICU
// INIT - let i=0
// CONDITION -  i< 10
// UPDATION

// for( i;c;u){

// }

// for(let i=0;i<10;i++){
//     // code that you want to repeat!
//     console.log(i);
// }

for(let i=0;i<10;++i){
    console.log(i);
}
Text
0
1
2
3
4
5
6
7
8
9
A cheat sheet titled Anatomy of a for Loop. The header for (let i = 0; i < 10; i++) is split by three brackets: let i = 0 is marked 1, Init: runs once; i < 10 is marked 2, Condition: checked before every pass; i++ is marked 3, Update: after every pass, with an arrow from 3 back to 2. A red banner at the bottom reads: Condition false: the loop stops.
From the batch repo's README: the three parts of the header, and the order they run in.

One pass at a time:

Pass Check Prints Update
1 0 < 10: true 0 i becomes 1
2 1 < 10: true 1 i becomes 2
3 2 < 10: true 2 i becomes 3
4 3 < 10: true 3 i becomes 4
5 4 < 10: true 4 i becomes 5
6 5 < 10: true 5 i becomes 6
7 6 < 10: true 6 i becomes 7
8 7 < 10: true 7 i becomes 8
9 8 < 10: true 8 i becomes 9
10 9 < 10: true 9 i becomes 10
10 < 10: false the loop ends

When i reaches 10, 10 < 10 is false and the loop ends, so the last value printed is 9: ten values, 0 to 9. Two follow-ups from class:

  • Include the 10? Change the condition to i <= 10, and 10 is counted too.
  • i++ or ++i? No difference. The file uses ++i, and the class notes put it plainly: use whichever you want, pre or post. Nothing reads the update's value, so either one just adds 1.
05

Loop boundaries: any name, < or <=, zero runs and infinite loops

Then came interview drills on the loop header, one question per file. Most of them were commented out once the class had run them.

Can the counter have any name? Yes, any valid name. This one counts with age instead of i:

JavaScript
// for (let age = 0; age < 10; age++) {
//     console.log(age);
// }

The whole file is commented out, so it prints nothing. Switched on, it prints 0 to 9, exactly like file 64.

Start at 1 and use <=:

JavaScript
for (let age = 1; age <= 10; age++) {
    console.log(age);
}
Text
1
2
3
4
5
6
7
8
9
10

1 to 10, and 10 is included, because 10 <= 10 is true.

Is _1 a valid name? File 67 holds two questions, both commented out:

JavaScript
// for (let _1 = 0; _1 <= 10; _1++) {
//     console.log(_1);
// }

// for (let pramod = 0; pramod > 1; pramod++) {
//     console.log(pramod);
// }

The first is valid syntax: a name may start with an underscore, so _1 is a valid identifier. Switched on, it prints 0 to 10, eleven values, with both ends included:

Text
0
1
2
3
4
5
6
7
8
9
10

The second prints nothing at all. pramod starts at 0, and 0 > 1 is false on the very first check, so the body never runs. It is not an infinite loop either: a loop that never starts cannot run forever.

No condition at all:

JavaScript
// for (let pramod = 0; ; pramod++) {
//     console.log(pramod);
// }

With the middle of the header empty, nothing ever stops the loop, and pramod keeps growing. Switched on, it prints 0, 1, 2 and keeps going until you stop it with Ctrl+C. Its first five lines:

Text
0
1
2
3
4

That is why the file stays commented out. Do not write a loop without a condition.

FIVE LOOP HEADERS, AND THE VALUES THE COUNTER TAKES for(let i=0;i<10;++i) 0 1 2 3 4 5 6 7 8 9 10 10 runs for (let age = 1; age <= 10; age++) 1 2 3 4 5 6 7 8 9 10 11 10 runs for (let _1 = 0; _1 <= 10; _1++) 0 1 2 3 4 5 6 7 8 9 10 11 11 runs for (let pramod = 0; pramod > 1; pramod++) 0 0 runs for (let pramod = 0; ; pramod++) 0 1 2 3 4 5 6 7 ... never stops The dashed cell is the first value the condition rejects: it is checked, but never printed.
Read the first value, the last value and the count. The value that ends a loop is checked but never printed, and a loop with no condition never ends.
06

if inside a loop: the gift question

A very famous question mixes a for loop with an if: in which years does the gift arrive? The loop counts the ages from 0 to 17. Over 15, the gift is an iPhone; until then, no gift.

JavaScript
for (let age = 0; age < 18; ++age) {
    if (age > 15) {
        console.log("Gift from papa, iphone this year")
    } else {
        console.log("No Gift, iphone only barbie doll")
    }
}
Text
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
No Gift, iphone only barbie doll
Gift from papa, iphone this year
Gift from papa, iphone this year
Age Check Prints
0 to 15 age > 15: false, 16 times No Gift, iphone only barbie doll (16 lines)
16 16 > 15: true Gift from papa, iphone this year
17 17 > 15: true Gift from papa, iphone this year
18 18 < 18: false nothing: the loop ends
EIGHTEEN PASSES, ONE CHECK EACH: IS THE AGE OVER 15? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 FALSE: AGES 0 TO 15 No Gift, iphone only barbie doll printed 16 times TRUE: AGES 16 AND 17 Gift from papa, iphone this year printed 2 times Age 18 never gets a pass: 18 < 18 is false, so the loop ends before the if is reached.
One loop, one decision per pass. Two gifts: the if is true only at 16 and 17, and the loop stops before 18.

Two gifts, at 16 and 17. Age 18 never gets a pass, because 18 < 18 is false. And changing ++age to age++ changes nothing: as in file 64, the form of the update makes no difference to a for loop.

07

The while loop

while has the same three parts as the for loop, spread out: the init goes before the loop, the condition goes in the header, and the update goes inside the body. From the class notes: while is generally used when a condition is the main thing. Use it when you do not know how many times the loop will run.

JavaScript
// While
// ICU
let i = 0;

while (i < 10) {
    console.log(i);
    i++;
}

// let i1 = 0;
// for ( ;i1 < 10; i1++) {
//     console.log(i1);
// }
Text
0
1
2
3
4
5
6
7
8
9

The same 0 to 9 as the for loop in file 64. Can a for loop keep its init outside, too? Yes. The commented lines at the end of 70.js do exactly that: the init sits on its own line and the header starts with a bare semicolon. The counter needs a new name, i1, because i is already taken in the file. Switched on, those lines print 0 to 9 as well. It works, but it is not how for loops are usually written.

A flowchart titled How a while Loop Runs. A yellow diamond holds the check attempts < 3. The true arrow leads to a box, Run the body, then down to a box, attempts++, and a curved arrow back to the diamond. The false arrow leads down to a red box, Exit the loop. A note with a light bulb reads: No update means it never ends.
From the batch repo's README: the while loop as a flowchart, on the retry counter from file 71.

A retry counter, the shape of the example in the class notes:

JavaScript
let attempts = 0; // Init

while (attempts < 3) {
    console.log("Attempt", attempts);
    attempts++;
}
Text
Attempt 0
Attempt 1
Attempt 2
Pass Check Prints Update
1 0 < 3: true Attempt 0 attempts becomes 1
2 1 < 3: true Attempt 1 attempts becomes 2
3 2 < 3: true Attempt 2 attempts becomes 3
3 < 3: false the loop ends

Count to 15:

JavaScript
let modi = 1;
while (modi <= 15) {
    console.log("Modi will do 15+ years");
    modi++;
}
Text
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years
Modi will do 15+ years

modi runs from 1 to 15, both included, so the line prints 15 times.

08

while (true) and break

while (true) on its own is an infinite loop: the condition can never turn false. The way out is the break keyword. From the class notes: whenever break is used, it puts you out of the loop; it terminates the loop.

JavaScript
let age = 7;
while(true){
    if( age > 10){
        break;
    }else{
        console.log(age);
    }
    age++;
}

Before running it, the class had to choose: does it print 7, 8, 9, 10, or 7, 8, 9?

Pass Check What happens
1 7 > 10: false the else prints 7, then age becomes 8
2 8 > 10: false the else prints 8, then age becomes 9
3 9 > 10: false the else prints 9, then age becomes 10
4 10 > 10: false the else prints 10, then age becomes 11
5 11 > 10: true break: out of the loop, nothing printed
Text
7
8
9
10

7 to 10. At 10, 10 > 10 is false, so the else still prints 10. Only at 11 is the check true, and break leaves the loop before anything is printed. This one is a very important interview question.

09

do...while: the loop that runs at least once

do...while is the loop that always runs at least once. From the class notes: it will always execute at least one time, which makes it the loop for retrying a flaky action, and it is used a lot in automation. The body comes first, in a do block, and the condition comes after it:

JavaScript
let retry = 0;

do {
    console.log("Executing the code....");
    console.log("Retrying.....",retry);
    retry++;
} while (retry < 3);
Text
Executing the code....
Retrying..... 0
Executing the code....
Retrying..... 1
Executing the code....
Retrying..... 2
Pass Prints Update Check after the body
1 Executing the code.... and Retrying..... 0 retry becomes 1 1 < 3: true, go again
2 Executing the code.... and Retrying..... 1 retry becomes 2 2 < 3: true, go again
3 Executing the code.... and Retrying..... 2 retry becomes 3 3 < 3: false, stop

Inside each pass the order is: the two lines print, retry++ runs, and only then is retry < 3 checked. So the retry count prints as 0, 1 and 2, and 3 never prints. Two details from class:

  • The semicolon after while (retry < 3) belongs there. Semicolons are optional in JavaScript, but do not forget this one.
  • Forget retry++ and retry stays 0, 0 < 3 is always true, and the loop never ends. The class ran it to see, and had to stop it.
10

while or do...while

The difference, on the same start value and the same condition. File 75 keeps the while version in comments and runs the do...while version:

JavaScript
// Do while vs while


// while -- While will always check the condition first. 
// let a = 10;
// while(a < 10){
//     console.log(a);
//     a++;
// }

let a = 10;
do {
    console.log(a);
    a++;
} while (a < 10);
Text
10
  • while checks first. a is 10, 10 < 10 is false, so the body never runs and nothing prints. Run the five commented lines on their own and that is what you get. (Switched on in place, their let a clashes with the second one, and the file stops with SyntaxError: Identifier 'a' has already been declared.) Because while checks the condition before it lets you in, the class calls it an entry loop: you enter only when the condition is true.
  • do...while runs first. It prints 10, a becomes 11, and only then is 11 < 10 checked. That is false, so it stops. The body ran once.
Two panels showing the same closed door with an unlit lamp above it. Left, titled while, with the sublabel Check first: a magnifying glass beside the unlit lamp and a terracotta line across the doormat; the door stays shut. Right, titled do while, with the sublabel Knock at least once: the door knocker strikes once, with terracotta motion marks and a small retry arrow, while the lamp is still unlit.
while checks before it lets you in, so it can run zero times; do...while knocks first and checks after, so it always runs once.
A comparison titled while vs do...while, starting from a = 10. Left column, while: while (a < 10) { ... }, check, then run, and a red bar: runs 0 times. Right column, do...while: do { ... } while (a < 10);, run, then check, and a green bar: runs 1 time. A banner at the bottom reads: do...while always runs at least once.
From the batch repo's README: file 75 in one picture. Same start, same condition, a different count.

The rule to remember: do...while always runs its body at least once.

11

Nested loops, and the loops still to come

Can a loop sit inside a loop? Yes, a for loop inside a for loop. File 76 shows the shape:

JavaScript
// Nested the For Loop
// 1 Array - W

for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        console.log(i, j);
    }
}
Text
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
Outer pass Inner loop Prints
1, i is 0 j is 0, then 1, then 2 0 0, 0 1, 0 2
2, i is 1 j is 0, then 1, then 2 1 0, 1 1, 1 2
3, i is 2 j is 0, then 1, then 2 2 0, 2 1, 2 2
3 < 3: false the outer loop ends after 9 lines

For every pass of the outer loop, the inner loop runs all the way through: 3 x 3, nine lines. To use nested loops for real you need arrays first, so they come back after arrays. So do three more kinds of loop: for...of, for...in and forEach. From the class notes: they come when we use the array, and for matrices.

12

Five loop output questions

Five questions from the class notes, all marked easy. They are trickier than they look, so solve each one with pen and paper before you read the answer.

Q1. Which loop is guaranteed to execute its body at least once, even when its condition is initially false? A) for, B) while, C) do...while, D) all three.

Answer: C, do...while. It runs the body before it checks.

Q2. What is the output? A) 0 1 2, B) 1 2 3, C) 0 1 2 3, D) 1 2

JavaScript
for (let i = 0; i < 3; i++) {
  console.log(i);
}
Text
0
1
2

Answer: A. 3 is not counted, because 3 < 3 is false.

Q3. What is the output? A) 4, B) 5, C) 0, D) infinite loop

JavaScript
let i = 0;
while (i < 5) {
  i++;
}
console.log(i);
Pass Check Body
1 0 < 5: true i++: i becomes 1, nothing printed
2 1 < 5: true i++: i becomes 2, nothing printed
3 2 < 5: true i++: i becomes 3, nothing printed
4 3 < 5: true i++: i becomes 4, nothing printed
5 4 < 5: true i++: i becomes 5, nothing printed
5 < 5: false the loop ends; console.log(i) prints 5
Text
5

Answer: B, 5. This is the one that catches people. Nothing prints inside the loop; the body only adds 1. The single console.log runs after the loop, and the loop only exits once i is 5.

Q4. What is the output? A) prints 10, B) prints nothing, C) prints 10 five times, D) infinite loop

JavaScript
let i = 10;
do {
  console.log(i);
} while (i < 5);
Text
10

Answer: A, it prints 10. Some will say infinite loop. It is not: do...while runs the body once, then 10 < 5 is false, and it stops.

Q5. What is the output? A) 0, B) 5, C) 1, D) infinite loop. It is file 77 in the repo:

JavaScript
let count = 0;
for (let i = 5; i < 5; i++) {
  count++;  
}
console.log(count);
Text
0

Answer: A, 0. i starts at 5, and 5 < 5 is false, so count++ never runs.

Where the output shows up. A question from class: why does the terminal stay empty when the instructor runs a file? The run button in VS Code shows the output in the Output panel. It appears in the terminal only when you run the file with node yourself.

13

Tasks and announcements

  • Today's task: the triangle classifier, on the coding platform at app.thetestingacademy.com, under Playwright, coding practice. It is about the three types of triangle: equilateral, where all three sides are equal; isosceles, where two sides are equal; and scalene, where no side is equal. Meeti adds it as today's task. The pyramid problems wait until after Monday's class.
  • The coding platform is for submitting, which earns points, not for practice. Practise in your own editor.
  • Sunday test at 7 AM IST. Do not miss it.
  • No master class this evening. Instead, around 8 PM IST, the recorded Claude 101 master class, about an hour long, goes up in the group. Claude 101 is the batch's first certification: watch the video, create a free account, take the test, and get the certificate from Anthropic at the end. Then post it on LinkedIn and tag Pramod Dutta. If you have already done it, skip it.
  • Doubts go in the doubt thread, since raise hand was not working in class; the instructor answers them one by one. Examples with strings, and where while loops are used in automation, come later.
  • The push. The class's code went up with /go, near the end of class.
  • Coming up: arrays, then nested loops and the for...of, for...in and forEach loops. A learner asked how to print the numbers on one line instead of one per line; that comes later too.

Task, triangle classifier. Solve the triangle classifier on the coding platform: from the three sides, decide whether a triangle is equilateral, isosceles or scalene.

Task, Claude 101. Watch the recorded master class, take the Claude 101 test, then post your certificate on LinkedIn and tag Pramod Dutta.