This article will quickly explain nested for loops in JavaScript, how they are used with multidimensional arrays, and show some examples.
For Loops
We’ve already covered for loops – check out our article here.
To sum up the article, for loops repeat a block of code for a given number of iterations:
for (let i = 0; i <= 3; i++) { console.log(i); // Will output the numbers 0-3 to the console }
Above, a for loop is defined that defines an initial variable i that is used to control the loop, sets a condition that it should loop so long as i <= 3 and should increment i by 1 after each time the loop runs.
As the code in the loop runs, the current value i is printed in each iteration.
Nesting Loops in JavaScript
In JavaScript loops can be placed inside other for loops:
for (let i = 0; i <= 3; i++) { // Note that the variable used to track the state of the loop is i console.log("Outer: " + i); // Will output the numbers 0-3 to the console for (let j = 1; j <= 2; j++) { // Note that the variable used to track the state of the loop is j , a different variable than the one used for the outer loop console.log("Inner: " + j); // Will output the numbers 0-2 to the console } }
Note that when nesting for loops, you should use a different variable name to track the state of each loop if you want them to operate independently. If you do not do this, the inner loop will still increment independently (as the variables are scoped) – it just makes your code far more confusing to read and increases the chances of bugs appearing.
The above code will output:
Outer: 0 Inner: 1 Inner: 2 Outer: 1 Inner: 1 Inner: 2 Outer: 2 Inner: 1 Inner: 2 Outer: 3 Inner: 1 Inner: 2
Above, you can see the outer loop incrementing. For each iteration of the outer loop, the inner loop is run in full. Any nested loops will complete before their parent loop moves onto its next iteration.
You can nest as many loops as your like, with as many loops at as many levels as required.
Why Nest Loops?
Why would you want to nest loops? Nested loops are most commonly used to process tabulated data. Tabulated data is organised into rows and columns. To iterate over each value in each row/column, you need to loop over each row, and separately loop over each column within it. Nesting loops accomplishes this.
Multidimensional Arrays
Multidimensional arrays are arrays inside arrays. Each nested array is a dimension. Tabulated data in rows and columns thus has two dimensions – a 2D array.
var twoDimensionalArray = [ ['a1', 'a2', 'a3', 'a4'], ['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3', 'c4'] ];
Above, a two dimensional array is defined. The outer array (noted by the outer pair of square brackets) contains the rows. Each row is itself an array, which contains the values for each column, in the order that they should appear in the table.
In the above example, I’ve given everything on the first row the prefix a, followed by the column number, everything on the second row the prefix b followed by the column number, and so on.
If each value in a row needs to have a consistent value with other rows (ie, the data is organised into columns for name, age, height, if describing a person), all rows must follow that same order.
Further Dimensions
You can nest arrays inside arrays, inside arrays (that would be 3 dimensions). There’s no limit to how many arrays you can nest. 3D arrays could be used to represent the position of objects in 3D space for a video game, for example.
Code Examples
Below are some code examples showing how nested for loops can be nested to loop over multidimensional arrays.
Two Nested for Loops
The below code demonstrates nested for loops to a depth of 2, looping over a 2d array:
var twoDimensionalArray = [ ['a1', 'a2', 'a3', 'a4'], ['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3', 'c4'] ]; // Loop through the rows for(let rowNumber = 0; rowNumber < twoDimensionalArray.length; rowNumber++){ // Loop through each column in the row for(let columnNumber = 0; columnNumber < twoDimensionalArray[rowNumber].length; columnNumber++){ // Print the index of the outer and inner arrays console.log('row: ' + rowNumber + ', column: ' + columnNumber); // Print the value stored at the current row, column position console.log(twoDimensionalArray[rowNumber][columnNumber]); }; };
Note that the rowNumber and columnNumber variables are used to control each for loop. The loops will run on the condition that each variable is less than the respective row/column count, so that all rows are processed, and all columns in each row are processed in turn:
The above JavaScript code will output:
row: 0, column: 0 a1 row: 0, column: 1 a2 row: 0, column: 2 a3 row: 0, column: 3 a4 row: 1, column: 0 b1 row: 1, column: 1 b2 row: 1, column: 2 b3 row: 1, column: 3 b4 row: 2, column: 0 c1 row: 2, column: 1 c2 row: 2, column: 2 c3 row: 2, column: 3 c4
Easier syntax – foreach
Nested for loops can be preferable in some situations when dealing with multidimensional arrays, specifically when you want more control over how the loop behaves by altering the variable used to control the loop.
If you’re just looking to loop over every variable in an array, consider using the forEach method of the JavaScript arrays instead – the syntax is a bit cleaner and easier to read:
// Declare a multidimensional array var twoDimensionalArray = [ ['a1', 'a2', 'a3', 'a4'], ['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3', 'c4'] ]; // Loop through the outermost array twoDimensionalArray.forEach(function(rowValue, rowIndex){ // Loop through each of the sub-arrays rowValue.forEach(function(columnValue, columnIndex){ // Print the index of the outer and inner arrays console.log('row: ' + rowIndex + ', column: ' + columnIndex); // Print the value stored at the current row, column position console.log(columnValue); }); });