JavaScript Loops

Comprehensive Learning Notes

Loops

Loops are control-flow structures that repeatedly execute a block of code as long as a specified condition is satisfied. They are essential for tasks such as:

Repeating operations a fixed number of times

Iterating through arrays and objects

Generating sequences (for example, Fibonacci numbers)

The following loop constructs are:

while loop
do...while loop

for loop

Nested loops

Loops with arrays

for...of loop

Loops with objects (for...in and object-to-array approaches)

break and continue (including in nested loops and labeled blocks)

2. while Loop

2.1 Concept and Syntax

A while loop executes its body as long as its condition evaluates to true.

Basic syntax:

js

while (condition) {
  // code that executes while condition is true
}

The condition is evaluated before each iteration.

If the condition is initially false, the loop body is skipped entirely.

2.2 Simple counting example

This example prints numbers from 0 up to (but not including) 10.

let i = 0;
while (i < 10) {
  console.log(i);

i = i + 1;

}

Line-by-line explanation:

let i = 0;
Declares a variable i and initializes it to 0; this is our loop counter.
while (i < 10) {
Starts the loop; the body will execute while i is less than 10.
console.log(i);
Outputs the current value of i to the console.

i = i + 1; Increments i by 1 so that the loop progresses toward the stopping condition.

When i reaches 10, the condition i < 10 becomes false and the loop stops.

ASCII trace of the variable i:

Iteration i before condition (i < 10?) i after

1 0 true 1

2 1 true 2

...

10 9 true 10

11 10 false (loop ends)

2.3 Searching in an array with while

Example: find a specific value in an array and stop when found, or when the array is exhausted.

let someArray = ["Mike", "Antal", "Marc", "Emir", "Louiza", "Jacky"];
let notFound = true;
while (notFound && someArray.length > 0) {
  if (someArray[0] === "Louiza") {
    console.log("Found her!");

notFound = false;

  } else {
    someArray.shift();
  }
}
console.log(notFound);

Explanation:

someArray holds several names.

notFound is a Boolean that indicates whether we have already found "Louiza". Initially it is true.

while (notFound && someArray.length > 0) {
The loop continues only while

we have not found the name yet, and

the array still has elements (length > 0). This prevents an infinite loop if the name is not present at all.

if (someArray[0] === "Louiza") { ... }
Checks whether the first element of the array is "Louiza".

If found:

Logs "Found her!".

Sets notFound to false, which will stop the loop in the next condition check.

Otherwise:

someArray.shift(); removes the first element, so the next name moves to index 0 for the next iteration.
After the loop completes, console.log(notFound); prints false if the name was found, or true if the array was exhausted without finding it.

2.4 Generating the Fibonacci sequence with while

Example: create an array containing the first 25 values of the Fibonacci sequence.

let nr1 = 0;
let nr2 = 1;
let temp;
let fibonacciArray = [];
while (fibonacciArray.length < 25) {
  fibonacciArray.push(nr1);

temp = nr1 + nr2;

nr1 = nr2;

nr2 = temp;

}
console.log(fibonacciArray);

Explanation:

nr1 and nr2 hold consecutive Fibonacci numbers, starting at 0 and 1.

temp is a temporary variable to store the next value in the sequence.

fibonacciArray starts as an empty array; we will fill it with Fibonacci numbers.

while (fibonacciArray.length < 25) {
Loops until the array contains 25 elements.
fibonacciArray.push(nr1);
Appends the current nr1 to the array.

temp = nr1 + nr2; Computes the next Fibonacci number as the sum of the two previous ones.

nr1 = nr2; and nr2 = temp; Shift the pair forward: what was nr2 becomes the new nr1, and temp becomes the new nr2.

The resulting array starts 0, 1, 1, 2, 3, 5, ... and quickly grows large.

3. do...while Loop

3.1 Concept and Syntax

A do...while loop guarantees that its body is executed at least once, because the condition is checked after the body runs.

Syntax:

js

do {

// code to execute at least once

} while (condition);

Use this when you must perform the action at least once—typical scenarios include user input prompts or connection attempts.

3.2 Validating user input between 0 and 100

Example: repeatedly ask the user for a number in a valid range.

let number;
do {
  number = prompt("Please enter a number between 0 and 100");
} while (!number || number < 0 || number > 100);
console.log("You entered:", number);

Explanation:

let number;
Declares a variable to hold the user’s input.
do { ... } while (...);
Ensures the prompt is shown at least once.

Inside the do block:

prompt("Please enter a number between 0 and 100") displays a dialog and returns a string typed by the user.

The result is assigned to number.

The while condition:

!number checks for an empty or cancel case.

number < 0 checks for too small values.

number > 100 checks for too large values. If any of these are true, the loop repeats and the user is prompted again.

Once the user enters a valid number, the loop exits and the final value is logged.

Control-flow diagram (simplified)

text

+------------------------------+

| Start |

+------------------------------+

|

v

Execute body

|

v

Evaluate condition

|

+--------+---------+

| |

true (repeat) false (exit)

| |

+------------------+

4. for Loop

4.1 Concept and general form

A for loop is a compact loop construct with three parts in its header:

for (initialization; condition; update) {

// code to execute each iteration

}

Execution order:

Execute initialization (once).

Evaluate condition. If false, exit the loop.

Execute the body.

Execute update.

Return to step 2.

4.2 Counting with for

Example: log numbers 0 through 9.

for (let i = 0; i < 10; i = i + 1) {
  console.log(i);
}

Explanation:

let i = 0; (initialization)
Declares and initializes loop counter i to 0.
i < 10; (condition)
The body executes only while i is less than 10.

i = i + 1 (update) Increments i by 1 after each iteration.

console.log(i);
Outputs the current value of i for each iteration.

4.3 Using for to build arrays

4.3.1 Array of integers 0 to 99

let arr = [];
for (let i = 0; i < 100; i = i + 1) {
  arr.push(i);
}
console.log(arr);

Explanation:

let arr = [];
Creates an empty array to store values.

The loop runs for i from 0 to 99.

arr.push(i);
Adds the current i to the end of arr in each iteration.

After the loop, arr contains 100 elements, from 0 to 99.

4.3.2 Array of even numbers from 0 to 98

let arr = [];
for (let i = 0; i < 100; i = i + 2) {
  arr.push(i);
}
console.log(arr);

Explanation:

Increments by 2 instead of 1, so i takes on values 0, 2, 4, ..., 98.

The result is an array of even numbers under 100.

5. Nested Loops

5.1 Concept

A nested loop is a loop inside another loop. For example:

js

while (condition1) {

// outer loop code

  while (condition2) {

// inner loop code

  }
}

Nested loops are commonly used for operating on two-dimensional data, such as tables, matrices, or arrays of arrays.

5.2 Creating an array of arrays with nested for loops

Example: build a 3×7 structure (3 rows, 7 columns), where each inner array contains the numbers 0 through 6.

js

let arrOfArrays = [];
for (let i = 0; i < 3; i = i + 1) {
  arrOfArrays.push([]);
  for (let j = 0; j < 7; j = j + 1) {
    arrOfArrays[i].push(j);
  }
}
console.log(arrOfArrays);
console.table(arrOfArrays);

Explanation:

let arrOfArrays = [];
Creates an empty array that will hold other arrays (rows).
Outer loop (for (let i = 0; i < 3; i = i + 1))
Runs 3 times, once for each row.
arrOfArrays.push([]);
Adds a new empty inner array for each row.
Inner loop (for (let j = 0; j < 7; j = j + 1))
Runs 7 times per row to fill columns.
arrOfArrays[i].push(j);
Appends the current j value (0–6) to the currently active row.

Resulting structure (conceptually):

js

[
  [0, 1, 2, 3, 4, 5, 6],
  [0, 1, 2, 3, 4, 5, 6],
  [0, 1, 2, 3, 4, 5, 6]
]
console.table(arrOfArrays); displays this neatly in tabular form in supporting consoles.

6. Loops and Arrays

6.1 Looping over arrays with for

General pattern:

js

let arr = /* some array */;
for (let i = 0; i < arr.length; i = i + 1) {
  // use arr[i]
}

The condition i < arr.length ensures that every valid index is visited exactly once and the loop stops after the last element.

6.2 Logging each array element

js

let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];
for (let i = 0; i < names.length; i = i + 1) {
  console.log(names[i]);
}

Explanation:

The loop counter i runs from 0 to names.length - 1.

names[i] accesses the element at position i.

Every name in the array is logged once.

6.3 Modifying every element in an array

Example: prepend "hello " to each name.

let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];
for (let i = 0; i < names.length; i = i + 1) {
  names[i] = "hello " + names[i];
}
console.log(names);

Explanation:

Inside the loop, names[i] is reassigned to a new string built by concatenating "hello " with the current value.

After the loop, the array contents are: "hello Chantal", "hello John", "hello Maxime", "hello Bobbi", "hello Jair".

6.4 Filtering or transforming with conditions

Example: remove names starting with "M" (using delete) and prepend "hello " to the others.

js

let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];
for (let i = 0; i < names.length; i = i + 1) {
  if (names[i].startsWith("M")) {
    delete names[i];

continue;

  }
  names[i] = "hello " + names[i];
}
console.log(names);

Explanation:

names[i].startsWith("M") checks if the current name begins with "M".

If it does:

delete names[i]; removes the property at index i, leaving a hole (an empty slot) rather than shifting elements.

continue; skips the rest of the current iteration and proceeds with the next iteration.

For all other names, "hello " is prepended.

The resulting array includes an “empty item” where the deleted element was, because delete does not reindex the array.

6.5 Infinite loop hazard when modifying array length

Problematic example (do not use):

js

let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];
for (let i = 0; i < names.length; i = i + 1) {
  names.push("...");
}

Explanation:

Each iteration adds a new element to the array with names.push("...").

This increases names.length continuously.

Because i is always less than the ever-growing names.length, the loop never terminates, creating an infinite loop.

7. for...of Loop

7.1 Concept and syntax

The for...of loop iterates directly over the values of an iterable, such as an array.

Syntax:

js

for (let variableName of array) {

// code that uses variableName

}

Interpretation: “For each value in array, call it variableName and execute the body.”

Unlike the for loop with an index, for...of is designed for processing values and does not provide direct control to modify the array elements by index inside the loop body.

7.2 Example: logging array values

js

let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];
for (let name of names) {
  console.log(name);
}

Explanation:

let name of names
On each iteration, name is assigned the next value from the names array.
console.log(name);
Logs the current name.

The loop automatically stops after all values have been processed.

Key points:

No index variable is needed; the code is concise and readable.

Because you are iterating over values, this pattern is ideal for reading or sending data elsewhere, but not for in-place modification by index.

8. Loops and Objects (Conceptual)

Chapter 5 also introduces looping over object properties (for example using for...in) and the idea of looping by first converting objects to arrays. The detailed patterns include:

Using for...in to iterate over an object’s enumerable keys.

Converting objects to arrays (for example using methods like Object.keys, Object.values, and Object.entries—discussed later in the book) and then iterating using array loops.

The core idea is:

For arrays, prefer index-based for loops or for...of when you just need values.

For objects, use property-based loops (for...in) or array conversion followed by array-oriented loops.

9. break and continue in Loops (Conceptual)

9.1 break

break immediately terminates the nearest enclosing loop and continues execution after the loop.

Useful when you find what you were searching for and do not want further iterations.

9.2 continue

continue skips the rest of the current iteration and moves directly to the next iteration’s condition check.

Useful for skipping certain elements (for example, filtering).