0
0
Javascriptprogramming~5 mins

Nested loops in Javascript

Choose your learning style9 modes available
Introduction

Nested loops let you repeat actions inside other repeated actions. This helps when you work with things like tables or grids.

When you want to print a grid of stars or numbers.
When you need to check every pair of items in two lists.
When you want to create a multiplication table.
When you process rows and columns in a spreadsheet.
When you want to combine every item from one list with every item from another.
Syntax
Javascript
for (let i = 0; i < outerLimit; i++) {
  for (let j = 0; j < innerLimit; j++) {
    // code to repeat
  }
}

The outer loop runs first, then the inner loop runs completely for each outer loop step.

Use different variable names for each loop to avoid confusion.

Examples
This prints pairs of i and j values for each step of the outer and inner loops.
Javascript
for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 2; j++) {
    console.log(`i=${i}, j=${j}`);
  }
}
This example shows how to loop through rows and columns like in a table.
Javascript
for (let row = 1; row <= 2; row++) {
  for (let col = 1; col <= 3; col++) {
    console.log(`Row ${row}, Column ${col}`);
  }
}
Sample Program

This program prints 3 rows of 4 stars each, making a simple star grid.

Javascript
for (let i = 1; i <= 3; i++) {
  let line = '';
  for (let j = 1; j <= 4; j++) {
    line += '* ';
  }
  console.log(line);
}
OutputSuccess
Important Notes

Nested loops can slow down your program if used with large limits because they repeat many times.

Always check your loop limits to avoid infinite loops.

Summary

Nested loops run one loop inside another to handle repeated tasks in layers.

They are useful for working with grids, tables, or pairs of items.

Remember to use different variables for each loop and watch the limits.