var arr = [[1,2], [3,4], [5,6]];

This is an array of arrays. It is a little bit easier to read like this:

var arr = [
            [1,2],
            [3,4],
            [5,6]
          ];

That makes it a little bit easier to see that you have an array of 3 arrays. The outer 'for' will loop through each of 1st level arrays. So the very first outer for loop when i=0 you are going to grab the first inner array [1,2]:

for (var i=0; i < arr.length; i++) {
    //First time through i=0 so arr[i]=[1,2];
}

In the inner loop you are going to loop through each of the 3 inner arrays one at a time.

for (var j=0; j < arr[i].length; j++) {
    //Handle inner array.
}

This argument grabs the length of the inner array:

arr[i].length

So on your first time through the outer loop i=0 and arr[i] is going to equal [1,2] because you are grabbing the 0th element. Remember, arrays elements are always counted starting at 0, not 1.

Finally you are printing out the results with:

console.log(arr[i][j]);

The first time through you can break it down a little. i=0 and j=0. arr[0][0] which translates as grab the first element from the outer array and then the first element from the first inner array. In this case it is '1':

[
    [1,2], <-- 0
    [3,4], <-- 1
    [5,6]  <-- 2
];

The code will loop through the first first set [1,2], then the second [3,4], and so on.

Answer from Gremash on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › nesting-for-loops-in-javascript
Nesting For Loops in JavaScript - GeeksforGeeks
Nesting for loops is crucial in JavaScript, enabling iteration over multi-dimensional data structures or performing complex tasks. It involves placing one loop inside another, where the outer loop executes for each iteration of the inner loop.
Published   August 5, 2025
🌐
W3Schools
w3schools.com › jsref › jsref_for.asp
JavaScript for Statement
A nested loop (a loop inside a loop): let text = ""; for (let = 0; i < 3; i++) { text += i + "<br>"; for (let j = 10; j < 15; j++) { text += j + "<br>"; } } Try it Yourself » · for is an ECMAScript1 (JavaScript 1997) feature.
Discussions

Understanding nested for loops in javascript - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I'm learning JavaScript at the moment on freecodecamp and they have an example for nested for loops in one of their excercises: More on stackoverflow.com
🌐 stackoverflow.com
Nested For Loops
Hey all. First time poster on FCC. I tried algorithm scripting with high difficulties like others. So I wanted to take a step back and look at nested for loops to increase my understanding. I’m attempted to printout a so… More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
July 22, 2020
Javascript - Avoiding variable redundancy in nested for loops - Software Engineering Stack Exchange
Please bear with me, I could only explain the problem in the comments of the code snippet below. Please read through them carefully. Question at the end: I usually tend to name the variables used ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
September 23, 2013
Finding it difficult to Understand Nested Loops
No, you should not move on. If you don't get nested loops, you don't get loops in the first place. A nested loop is just a loop inside another loop, and both loops behave as loops are supposed to. Do you understand that imperative programs are executed step by step? That a command can change the contents of a variable or an object? x = x + 1; would be false in math, but is a meaningful command in JS. More on reddit.com
🌐 r/learnjavascript
25
10
March 27, 2023
🌐
freeCodeCamp
freecodecamp.org › news › nesting-for-loops-in-javascript
Nesting For Loops in JavaScript
June 2, 2020 - Because arr is a multi-dimensional array, you'll need two for loops: one to loop through each of the sub-arrays arrays, and another to loop through the elements in each sub-array.
Top answer
1 of 7
21
var arr = [[1,2], [3,4], [5,6]];

This is an array of arrays. It is a little bit easier to read like this:

var arr = [
            [1,2],
            [3,4],
            [5,6]
          ];

That makes it a little bit easier to see that you have an array of 3 arrays. The outer 'for' will loop through each of 1st level arrays. So the very first outer for loop when i=0 you are going to grab the first inner array [1,2]:

for (var i=0; i < arr.length; i++) {
    //First time through i=0 so arr[i]=[1,2];
}

In the inner loop you are going to loop through each of the 3 inner arrays one at a time.

for (var j=0; j < arr[i].length; j++) {
    //Handle inner array.
}

This argument grabs the length of the inner array:

arr[i].length

So on your first time through the outer loop i=0 and arr[i] is going to equal [1,2] because you are grabbing the 0th element. Remember, arrays elements are always counted starting at 0, not 1.

Finally you are printing out the results with:

console.log(arr[i][j]);

The first time through you can break it down a little. i=0 and j=0. arr[0][0] which translates as grab the first element from the outer array and then the first element from the first inner array. In this case it is '1':

[
    [1,2], <-- 0
    [3,4], <-- 1
    [5,6]  <-- 2
];

The code will loop through the first first set [1,2], then the second [3,4], and so on.

2 of 7
9

The double for loop you have above works like so:

 var arr = [[1,2], [3,4], [5,6]];

 for (var i=0; i < arr.length; i++) {
  // i = 0, then we loop below:
  for (var j=0; j < arr[i].length; j++) {
    //here we loop through the array which is in the main array
    //in the first case, i = 0, j = 1, then we loop again, i = 0, j = 1
    console.log(arr[i][j]);
    //after we finish the stuff in the 'j' loop we go back to the 'i' loop 
    //and here i = 1, then we go down again, i, remains at 1, and j = 0, then j = 1
    //....rinse and repeat, 
  }
}

In plain english:

We grab the first element in the main array, which is an array itself, we loop through that, and log at each index, this is terminated by our length condition in the second loop. We then move to to the next index of the main array, which is an array itself.... and so on, until we reach the end of the main array

To access and index in the main array, we need to use array[i] - that index holds an array - so to go INTO that array, we need to use array[i][j]

Hope that makes sense!

🌐
Khan Academy
khanacademy.org › computing › computer-programming › programming › looping › pt › nested-for-loops
Nested For Loops | Looping | Intro to JS
Learn for free about math, art, computer programming, economics, physics, chemistry, biology, medicine, finance, history, and more. Khan Academy is a nonprofit with the mission of providing a free, world-class education for anyone, anywhere.
🌐
Programiz PRO
programiz.pro › resources › js-nested-loop
Understanding Nested Loops in JavaScript
Now, let’s say we want a triangle instead of a square: ... A triangle grows with each row. ... The first row has 1 star → The loop runs 1 time. The second row has 2 stars → The loop runs 2 times. The third row has 3 stars → The loop runs 3 times. let height = 5; for (let i = 1; i <= height; i++) { let row = ""; for (let j = 0; j < i; j++) { row += "* "; } console.log(row); }
Find elsewhere
🌐
Softuni
js-book.softuni.org › chapter-06-nested-loops.html
6.1. Nested Loops · Programming Basics with JavaScript
Here is an example that illustrates nested loops. The aim is again to print a rectangle made of n *_ _n stars, in which for each row a loop iterates from 1 to n, and for each column a nested loop is executed from 1 to *n:
🌐
Codedamn
codedamn.com › news › javascript
Nested for loops in JavaScript: Why?
January 4, 2023 - for(var i=4;i<6;i++){ for(var j=4;j<5;j++){ console.log(i,j); } }Code language: JavaScript (javascript) The above example is also available in a codedamn playground for you to modify and run. The output for the above example is as shown below. ... Below given is an image of the flowchart of how a nested for loop executes.
Top answer
1 of 5
10

One common approach, which is also used in the code you posted is to simply to use the next letter in the alphabet, so:

for(var i = 0; i < length; i++) {
    for(var j = 0; j < length; j++) {
        for(var k = 0; k < length; k++) {
            // More loops?
        }
    }
}

This approach is lazy, but it works. However, I find that it can get confusing when you're not looping the same array or accessing a multi-dimensional array. In that case, a better approach might be to simply provide more meaningful names:

for(var nameIndex = 0; nameIndex < names.length; nameIndex++) {
    for(var classroomIndex = 0; classroomIndex < classrooms.length; classroomIndex++) {
        // And so forth
    }
}

Of course this may be a little wordy for you, but I figure better a little wordy than completely uncomprehensible code. You were probably hoping for a neat hack here to be able to keep the i variable in its own scope. There may even exist a way to do so, however I don't believe in that kind of solution to a problem like this for two reasons:

  • Nested loops should generally be discouraged anyway. You cannot apply a best practice in a situation in which you're not following a best practice. Call a method instead.
  • It would leave the next programmer scratching his head wondering why you did it that way, and it is difficult to justify such a decrease in readability just to account for name clashing.

I hope that helps!

2 of 5
14

Simple:

  // This block with a
  // VERY
  // COMPLEX
  // operation
  // here
  // is far too large.

When blocks become so large that you cannot see all of your local variable definitions any more, they are definitely too large. Refactor such a parts to a function, this will help a lot to avoid accidentally double declarations.

🌐
EDUCBA
educba.com › home › software development › software development tutorials › javascript tutorial › nested loop in javascript
Nested Loop in JavaScript | Guide to Nested Loop - Flowchart & Examples
June 28, 2023 - JavaScript supports the nested loop feature, where a loop is present inside another loop. A loop can have one or number and/or n nested levels of loops defined inside another loop. For each outer loop, the inner loop gets to execute.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Dannyguo
dannyguo.com › blog › how-to-break-and-continue-in-nested-loops-in-javascript
How to Break and Continue in Nested Loops in JavaScript
April 17, 2022 - const chunks = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; chunkLoop: for (const chunk of chunks) { for (const number of chunk) { if (number === 5) { continue chunkLoop; } console.log(number); } } /* Output: 1 2 3 4 7 8 9 */ 5 and 6 aren’t in the output because when the code reaches 5, the code continues on to the next iteration of the chunk loop, which is the [7, 8, 9] chunk. ← How to Check if a JavaScript String Begins or Ends With a String How to Use Newlines in an Environment Variable File for Docker →
🌐
TutorialsPoint
tutorialspoint.com › how-to-use-nested-for-loop-in-javascript
How to use nested for loop in JavaScript?
November 10, 2022 - We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the name suggests, is made up of more than one for loop one nested inside of the other. This allows
🌐
Reddit
reddit.com › r/learnjavascript › finding it difficult to understand nested loops
r/learnjavascript on Reddit: Finding it difficult to Understand Nested Loops
March 27, 2023 -

I've been learning Js for 2 weeks now and at this point I'm stuck at Nested loops - I really can't grab the whole concept around nested loops, let alone the exercises ( like building a pyramid ).

Should I move on with other subjects in js hoping I won't meet nested loops on my path or I'll get familiar as time goes by?

🌐
LambdaTest Community
community.lambdatest.com › general discussions
Understanding Nested For Loops in JavaScript Arrays - LambdaTest Community
October 24, 2024 - I’m currently learning JavaScript on FreeCodeCamp, and I encountered an example involving nested for loops in JavaScript in one of their exercises: var arr = [[1, 2], [3, 4], [5, 6]]; for (var i = 0; i < arr.length; i++…
🌐
Sololearn
sololearn.com › en › Discuss › 249739 › nested-for-loops-in-js
Nested for loops in JS | Sololearn: Learn to code for FREE!
I can't figure out nested for loops. My head is spinning when I see two for loops one after the other. Can someone explain please? Am I missing a lesson or another explanation here? Thank you: var arr = [[1,2], [3,4], [5,6]];: for (var i=0; i < arr.length; i++) { for (var j=0; j < arr[i].length; j++) { console.log(arr[i][j]); } } javascriptarraysnestedforloop ·
🌐
Coding Rooms
codingrooms.com › blog › nested-loops-javascript
Nested Loops JavaScript
October 6, 2020 - The outer loop always executes first, and the inner loop executes inside the outer loop each time the outer loop executes once. Take a look at the example below and visualize how the nested loop works. for (counter = 1; counter < 4; counter++) ...
🌐
Scaler
scaler.com › home › topics › nested loop in javascript with examples
Nested Loop in JavaScript with Examples - Scaler Topics
January 1, 2024 - A. A nested loop in JavaScript is a loop placed inside another loop. It allows you to iterate over elements or perform repetitive tasks within a loop, which is part of another loop.
🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_nested_loop.htm
JavaScript - Nested Loop
In the following code snippet that demonstrates how we can use nested for loops. let rows = [1, 2, 3]; let columns = [4, 5, 6]; for (let i = 0; i < rows.length; i++) { for (let j = 0; j < columns.length; j++) { console.log(rows[i] + " " + columns[j]); } }