-2

If I put 'let tableValue' outside a while loop then it shows the same number 10 times and when I write it inside the while loop then it prints a table of the value 'n'.

What is 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);

function table(n) {
  let i = 1;
  while (i <= 10) {
    let tableValue = (n * i);
    console.log(tableValue);
    i++;
  }
}
table(9);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Samar
  • 137
  • 5
  • 2
    You're not updating/setting the value inside the loop on the first one. – Steven B. Oct 19 '21 at 01:29
  • 1
    What's hard to understand about it? If you don't reassign `tableValue` it doesn't change. – Barmar Oct 19 '21 at 01:34
  • Related: [Is JavaScript a pass-by-reference or pass-by-value language?](/q/518000/4642212). Why do you expect the two snippets to behave the same? Why do you believe the first one shouldn’t print `9` nine times? What do you think should happen instead? Why? [Rubber Duck Debug](//rubberduckdebugging.com/) your code. Please try using the [debugging capabilities](//ali-dev.medium.com/how-to-easily-debug-in-javascript-5bac70f94f1a) of your browser. Don’t just ask “Why are these different?”. Tell us why you believe they shouldn’t be. Otherwise, we’ll just say “Read the [spec](//tc39.es/ecma262)”. – Sebastian Simon Oct 19 '21 at 01:38
  • 1
    Duplicate of [Javascript - change variable value that is part of another variables definition](/q/42637782/4642212). – Sebastian Simon Oct 19 '21 at 01:44

2 Answers2

0

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.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

Use:

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 } don’t worry that it's inside the function, it still needs to be in the while block. I think that’s why you're getting confused.
  while (i <= 10) {
     console.log(tableValue);
     i++;
  }
}
table(9);

I’ve put comments on the line in which I think needs explaining.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kevo
  • 15
  • 7