Home > Software engineering >  Why does my Javascript loop only run once?
Why does my Javascript loop only run once?

Time:11-23

var board = ''
for (i=1;i<5;i  ){
  for (i=1;i<9;i  ){
    if (i%2 == 0){
      board  = "#";
    }
    else{
      board  = "O";
    }
  }
  board  = "\n"
  for (i=0;i<8;i  ){
    if (i%2 == 0){
      board  = "#";
    }
    else{
      board  = "O";
    }
  }
  board  = "\n"
}
console.log(board);

When I try to run this code, the output is

O#O#O#O#
#O#O#O#O

The intended output is

O#O#O#O#
#O#O#O#O
O#O#O#O#
#O#O#O#O
O#O#O#O#
#O#O#O#O
O#O#O#O#
#O#O#O#O

I tried adding a console.log(i) right after the first for statement and it only returns "1", meaning the loop only runs once. Why is this happening?

*Edit: When I wrap the two inner for loops in a function and call that instead, it works as intended

CodePudding user response:

You're

  • using the same variable name for each of your loops: i
  • not using block scope for those iteration variables with let

So all references to i in your code refer to the same binding.

At the end of the second inner loop - after for (i=0;i<8;i ){ - i is 8. Then, the outer loop:

for (i=1;i<5;i  ){

sees that i is not less than 5, so it stops.

Use a different variable name for each loop (eg i, j, and k), and declare your variables with let. Either will solve it, but implementing both is a good idea.

CodePudding user response:

I think that the problem is that you are reusing the same variable i in differents loops sentences.

For example. Below I use different variable names.


var board = ''
for (var j=1;j<5;j  ){
  for (var i=1;i<9;i  ){
    if (i%2 == 0){
      board  = "#";
    }
    else{
      board  = "O";
    }
  }
  board  = "\n"
  for (var k=0;k<8;k  ){
    if (k%2 == 0){
      board  = "#";
    }
    else{
      board  = "O";
    }
  }
  board  = "\n"
}
console.log(board);

CodePudding user response:

var board = ''
for (j=1;i<5;i  ){
  for (i=1;i<9;i  ){
    if (i%2 == 0){
      board  = "#";
    }
    else{
      board  = "O";
    }
  }
  board  = "\n"
  for (i=0;i<8;i  ){
    if (i%2 == 0){
      board  = "#";
    }
    else{
      board  = "O";
    }
  }
  board  = "\n"
}
console.log(board);

There's two loops, both index's "i". change one to 'j'

CodePudding user response:

I have tried experimenting with the code, and this is what I got:

var board = ''
for (i1=0;i1<4;i1  ){
  for (i2=0;i2<8;i2  ){
    if (i2%2 == 0){
      board  = "#";
    }
    else{
      board  = "O";
    }
  }
  board  = "\n"
  for (i3=0;i3<8;i3  ){
    if (i3%2 == 0){
      board  = "#";
    }
    else{
      board  = "O";
    }
  }
  board  = "\n"
}
console.log(board);

Gives me:

#O#O#O#O
#O#O#O#O
#O#O#O#O
#O#O#O#O
#O#O#O#O
#O#O#O#O
#O#O#O#O
#O#O#O#O

The problem was that the same variable (i) was getting reused, meaning that each loop resets the variable. Instead, I added numbers after the initial i.

  • Related