OneBite.Dev - Coding blog in a bite size

implement a two nested loop in Javascript

Code snippet on how to implement a two nested loop in Javascript

for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    console.log(i, j);
  }
}

This code creates two nested loops that run a total of 100 times. The first loop, the outer loop, runs the code 10 times and each time the inner loop runs 10 times for each iteration of the outer loop. The two loops are initiated with ‘let i = 0’ and ‘let j = 0’. Then comes the ‘i < 10’ which is the condition for the outer loop, meaning the loop will run until ‘i’ is no longer smaller than 10. The ‘j < 10’ is the condition for the inner loop.

After that, comes the code to be ran. In this case, it’s the ‘console.log(i, j)’ which, in each loop iteration, logs the iteration number of the outer and inner loop. The last part is ‘i++’ and ‘j++’ which increases the counters (i and j) by one. This way, the loop can move to the next iteration and continue. The whole loop will run until ‘i < 10’ and ‘j < 10’ is no longer true.

javascript