Categories
JavaScript Answers

How to use a for loop in multidimensional JavaScript array?

Spread the love

Sometimes, we want to use a for loop in multidimensional JavaScript array.

In this article, we’ll look at how to use a for loop in multidimensional JavaScript array.

How to use a for loop in multidimensional JavaScript array?

To use a for loop in multidimensional JavaScript array, we use a for-of loop.

For instance, we write

const arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9, 10],
];

for (const i of arr) {
  for (const j of i) {
    console.log(j);
  }
}

to use a nested for-of loop to loop through the elements.

We loop through the outer array with the outer loop.

Then we loop through the elements in each nested array with the inner loop.

i is the entry in the outer array being looped through.

j has the value of each entry in the nested array.

Conclusion

To use a for loop in multidimensional JavaScript array, we use a for-of loop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *