Home > Net >  JS why is my for loop push to array stopping after 1 itteration?
JS why is my for loop push to array stopping after 1 itteration?

Time:08-08

const say = console.log;

let grid = [];

for (i = 0; i < 5; i  ) {
  grid.push((i = [i, ""]));
  say(i);
}

why does this stop after only 1 iteration but if I put the push line into a function and call it, it works perfectly?

CodePudding user response:

You are changing the value of i to [0, ""] which isn't less than 5

Edit: To be 100% correct, first [0, ''] happens which probably throws an error

CodePudding user response:

You are assigning i to something that is not a number

const say = console.log;

let grid = [];

for (i = 0; i < 5; i  ) {
  grid.push([i, ""]);
  say(i);
}

needed to remove the i = [i, ""]

CodePudding user response:

Because after the first iteration

the value of i becomes [0, ""] 

whilst pushing into grid array, the value of "i" is getting modified and loop condition (i.e. [0,""] < 5) is getting failed, hence the loop breaks.

CodePudding user response:

The for loop is executed as long as the condition (i < 5) is true. In the push statement in your loop the expression (i = [i, ""]) overwrites the i variable. Therefore i contains [ 0, '' ]. Then the increment is executed, where javascript typecast i back to a number, which results in the NaN value. The comparison of NaN < 5 evaluates to false.

TLDR: You should avoid reassigning the variable i.

Edit: included the increment step as @Konrad Linkowsk noted

  • Related