nested loops in js

Nested loops in JavaScript are used when you need to perform repeated operations within another loop, allowing for the iteration over multidimensional arrays or complex data structures. For example:



Nested loops are a powerful concept in programming, and they have many real-life applications. Here are a few examples:

  1. Multiplication Tables: When you create a multiplication table, you use nested loops. The outer loop iterates through the rows, and the inner loop iterates through the columns to calculate the product of the row and column numbers.

  2. Seating Arrangements: Imagine organizing seating for a wedding. The outer loop could represent each table, and the inner loop could represent each seat at the table. This way, you can assign guests to specific seats at specific tables.

  3. Image Processing: When you apply filters to an image, you often use nested loops. The outer loop iterates through the rows of pixels, and the inner loop iterates through the columns of pixels, applying the filter to each pixel.

  4. Calendar Generation: Creating a calendar involves nested loops. The outer loop represents the months, and the inner loop represents the days within each month.

  5. Matrix Operations: In mathematics and computer science, operations on matrices (like addition, subtraction, and multiplication) use nested loops. The outer loop iterates through the rows, and the inner loop iterates through the columns of the matrix.


  1. Multiplication Tables:


for (let i = 1; i <= 10; i++) {
    let row = '';
    for (let j = 1; j <= 10; j++) {
        row += (i * j) + '\t';
    }
    console.log(row);
}
  1. Seating Arrangements:

let tables = 5;
let seatsPerTable = 4;
for (let table = 1; table <= tables; table++) {
    for (let seat = 1; seat <= seatsPerTable; seat++) {
        console.log(`Table ${table} Seat ${seat}`);
    }
}
  1. Image Processing (Applying a grayscale filter as an example):


let image = [
    [255, 128, 64],  // Each sub-array represents a pixel's RGB values
    [128, 64, 32],
    [64, 32, 16]
];

for (let i = 0; i < image.length; i++) {
    for (let j = 0; j < image[i].length; j++) {
        let avg = (image[i][j] + image[i][(j + 1) % 3] + image[i][(j + 2) % 3]) / 3;
        image[i][j] = avg;
    }
}
console.log(image);
  1. Calendar Generation:


const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

for (let month = 0; month < 12; month++) {
    console.log(`Month ${month + 1}:`);
    for (let day = 1; day <= daysInMonth[month]; day++) {
        console.log(`Day ${day}`);
    }
}
  1. Matrix Operations (Matrix multiplication as an example):

let A = [
    [1, 2],
    [3, 4]
];

let B = [
    [5, 6],
    [7, 8]
];

let result = [
    [0, 0],
    [0, 0]
];

for (let i = 0; i < A.length; i++) {
    for (let j = 0; j < B[0].length; j++) {
        for (let k = 0; k < A[0].length; k++) {
            result[i][j] += A[i][k] * B[k][j];
        }
    }
}

console.log(result);