Home > Net >  For nested in for - how it works?
For nested in for - how it works?

Time:09-06

I will appreciate it if somebody could explain to me how that program works. Do the loops start to count simultaneously or independently?

Thank you for your help!

let size = 8;
let board = "";

for (let y = 0; y < size; y  ) {
  for (let x = 0; x < size; x  ) {
    if ((x   y) % 2 == 0) {
      board  = " ";
    } else {
      board  = "#";
    }
  }
  board  = "\n";
}



CodePudding user response:

You have an inner and an outer loop. The outer loop starts on the 3rd line and uses “Y” as a variable. It will loop 8 times. On each of the 8 outer loops, another inner loop will run 8 times (the loop using the "x" variable).

So the flow is: the outer loop starts on iteration 1, then the inner loop runs 8 times, then the outer loop goes into iteration 2, and the inner loop runs 8 times, etc. They do not run concurrently. Does this help?

Here is a more detailed explanation: https://www.educba.com/nested-loop-in-javascript/

CodePudding user response:

The easiest explanation for followers

console.log("------ FIRST EXAMPLE -----");

for (let i = 0; i < 5; i  ) {
  console.log(`The current value of i is ${i}`);
  for (let j = 0; j < 5; j  ) {
    console.log(`j: ${j}`);
  }
  console.log("----------");
}

console.log("------ SECOND EXAMPLE -----");

for (let i = 0; i < 11; i  ) {
  for (let j = 0; j < 11; j  ) {
    console.log(`${i} x ${j}`);
  }
  console.log("----------");
}

  • Related