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);
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.
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.