Page Content

Tutorials

What are Nested Loops in JavaScript Development?

Nested Loops in JavaScript

A basic idea in JavaScript control flow is nested loops, which are loops inside loops. When you have to conduct a series of actions repeatedly and then another series of repeated actions within each repetition, you utilise this structure. Generally speaking, loops allow us to repeatedly run a specific code block until a condition is satisfied. Loops offer a more effective method of handling such activities or iterating over data sets like arrays and objects than continually copying a small amount of code.

The while loop, do while loop, for loop, for in loop, and for of loop are among the various JavaScript loop types that can be nested. Loops can be mixed (a while loop inside a for loop) or nested with the same type (a for loop inside a for loop, for example). Nesting can occur at multiple levels.

How Nested Loops Work

There is an inner loop and an outer loop in a nested loop construction. All inner loop iterations are completed for every outer loop iteration. The inner loop, like the second hand of a clock, rotates fully while the outer loop, the minute hand, only travels one step.

The general flow for nested for loops, which are frequently employed for this pattern, is as follows:

  1. The initialisation of the outer loop is done just once.
  2. The condition of the outer loop is examined. Its code block is run if it is true.
  3. The inner loop is encountered within the block of the outer loop.
  4. The initialisation of the inner loop is carried out just once.
  5. The state of the inner loop is examined. Its code block is run if it is true.
  6. The final expression (also known as the update statement) is executed following the execution of the inner loop’s code block.
  7. The inner loop ends when its condition turns false, which is achieved by repeating steps 5 and 6.
  8. The outer loop is where execution returns. The last expression of the outer loop is executed.
  9. Repeated, this time verifying the state of the outer loop. If so, the body of the outer loop runs, while the inner loop begins its cycle anew at step 4.
  10. This procedure keeps going until the condition of the outer loop is false and the nested loop structure as a whole is completed.

Code Example: Nested for Loops for Multiplication Tables

Making a multiplication table is a typical example that shows stacked for loops. The multiplier (1–12) and multiplicand (1–12) can be in outer and inner loops, respectively.

// Create multiplication tables from 1×1 up to 12×12
for (let i = 1; i <= 12; i++) { // Outer loop for multiplier
// Corrected: Use backticks for template literals
console.log(`— Table for ${i} —`); // Log the current table number
for (let j = 1; j <= 12; j++) { // Inner loop for multiplicand
// Inner loop runs completely for each value of i
// Corrected: Use backticks for template literals
console.log(`${i} multiplied by ${j} is ${i * j}`); // Log the calculation
}
}

The outer loop variable i in this instance begins at 1. Next, the inner loop logs 1 * 1, 1 * 2,…, 1 * 12 for j = 1 to 12. In the outer loop, i increases to 2 once the inner loop concludes (j reaches 13). Restarting the inner loop, j logs 2 * 1, 2 * 2,…, 2 * 12. This goes on until the outer loop is completed (I reaches 13).

Code Example: Nested while Loops

While less common than nested for loops for counter based tasks, you can also nest while loops:

let outerCount = 0;
while (outerCount < 3) { // Outer while loop
console.log(“Outer: ” + outerCount);
let innerCount = 0; // Inner loop variable initialized here
while (innerCount < 2) { // Inner while loop
console.log(” Inner: ” + innerCount);
innerCount++; // Update inner loop variable
}
outerCount++; // Corrected: Update outer loop variable
} // Corrected: Closing brace for the outer loop

As with the for loop, the inner while loop executes for each outer while loop iteration. To prevent infinite loops, it’s crucial to make sure that the inner and outer loop conditions will finally turn out to be false.

Controlling Flow in Nested Loops with break and continue

Nested loops can make use of the break and continue statements. Break or continue only applies to the innermost loop it is contained within by default.

  • Only the inner loop will exit when there is a break in it. The outer loop will then pick up where it left off.
  • In the inner loop, a continue will go on to the following inner loop iteration and bypass the remainder of the current one. This has no effect on the outer loop.

Labelled statements containing break or continue can be used to control an outer loop from inside an inner loop. The loop that you wish to target is preceded by a label, which is an identifier followed by a colon.

// Example using labeled break
let groups = [
[“Martin”, “Daniel”, “Keith”],
[“Margot”, “Marina”, “Ali”],
[“Helen”, “Jonah”, “Sambikos”],
]; // Array declaration ends with a semicolon

outerloop: for (let i = 0; i < groups.length; i++) { // Outer loop with label
let matches = 0; // Statement ends with a semicolon
innerloop: for (let j = 0; j < groups[i].length; j++) { // Inner loop with label
if (groups[i][j].startsWith(“M”)) { // startsWith() is a string method
matches++; // Statement ends with a semicolon
} else {
continue innerloop; // Continue the inner loop (label optional but good for clarity)
}
// This check runs after the if/else for each member
if (matches === 2) { // Condition check
console.log(“Found a group with two names starting with an M:”); // console.log() outputs to the console
console.log(groups[i]); // Accessing array elements by index
break outerloop; // Break the outer loop using the label – Semicolon required after break label
}
} // Inner loop block ends, no semicolon needed
} // Outer loop block ends, no semicolon needed
// Result: The first group with >= 2 names starting with ‘M’ is found, and the search stops.

In this case, breaking outerloop instantly ends the outer loop designated outerloop and halts the entire nested loop structure if we discover a group inside the inner loop with two names that begin with “M.” Break would only leave the inner loop without the label.

Although they are a great way to solve certain issues, like iterating over multidimensional arrays or creating data grids, nested loops can occasionally make code more difficult to read and even indicate “code smell.”  

Index