Reputation: 79
What's difference between returning out of curly-braces and in of it within for loops?
I have this code making 'factorial' in for loops code quiz of Udacity and it is marked as 'right answer' only if 'console.log(solution) is out of for loop braces. Why can I put it inside for loop? Can't really understand why is that.
var solution = 12;
for (var i = 1; i < 12; i++) {
solution = solution * i;
console.log(solution); /* Why inside of the loop like this is
wrong? */
}
var solution = 12;
for (var i = 1; i < 12; i++) {
solution = solution * i; // 12 = 1 * 2 * 3 * .... 12
}
console.log(solution); /* only it works when it's out of the loop
like this one but why???? */
Upvotes: 0
Views: 116
Reputation: 5527
The difference is that inside the loop you are outputting the contents, or the current state of solution
every time the loop repeats (in this case 11 times), when it's outside the loop body, you are only outputting the final state of the variable, or just 1 time.
Upvotes: 2