I have two simple functions here. In the loop function I have defined facky as one at the top of the function. Two things I do not understand:
console.log(loop(5)) is 120 when facky is defined at the top of loopvar facky = 1; within the while loop, the answer is 2. I understand why this is two. What I don't understand is why the behavior is different when the variable is outside?function loop(size) {
while (size > 1) {
var facky = 1;
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
function clunk(times) {
var num = times;
while (num > 0) {
console.log("clunk");
num = num - 1;
}
}
loop(5);
In your while loop, whenever the loop iterates, facky is reset to 1, so it will only print twice because the last iteration of the while loop multiplies facky by 2.
When you move the declaration outside of the while loop, facky does not reset after every iteration and takes on the value of 5!, or 120 after the final iteration.
You shouldn't declare a variable inside a loop. Try this instead:
function loop(size) {
var facky = 1;
while (size > 1) {
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
It doesn't really matter where you declare the var facky, it's always function-scoped.
What matters is whether you reset facky = 1 in every iteration of your loop, or whether you only initialise it once before the loop.