'Confusion in loops
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);
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
