Home > Blockchain >  Confusion in Loops
Confusion in Loops

Time:10-19

If I put 'let tableValue' outside while loop then it shows same number 10 times and when I write it inside while loop then it prints table of the value 'n'. I want to know the difference between these two things.

function table(n) {
  let i = 1;
  let tableValue = (n * i);
  while (i <= 10) {
    console.log(tableValue);
    i  ;
  }
}
table(9);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

function table(n) {
  let i = 1;
  while (i <= 10) {
    let tableValue = (n * i);
    console.log(tableValue);
    i  ;
  }
}
table(9);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If you put this line:

let tableValue = (n * i);

outside your loop, as you have in the first example, then tableValue is set once, before the loop begins, and when you log it, you are logging the same value each time, because you never change it after that.

This statement is not a declaration that tableValue is always n * i at all times, even when n and i change. If you want that, you need to recalculate tableValue whenever either of the values changes. That's what you're accomplishing by putting that line inside your loop.

Computers execute code one line at a time and don't look ahead or backward much. When code changes your program's state, such as setting a variable value, that change persists until it is later changed again.

CodePudding user response:

function table(n) {
  let i = 1;
  let tableValue = (n * i); // this is 1 * 9 , because it is outside the while loop ( the while loop block } dont worry that its inside the function, it still needs to be in the while block. I think thats why your getting confused.
  while (i <= 10) {
     console.log(tableValue);
     i  ;
  }
}
table(9);

Ive put comments on the line in which i think needs explaining

  • Related