If you see this output in the console, it's because the console displays the final result of the last statement executed in the program.
In this scenario, the for
loop produces a final value of 9
.
Although it may sound peculiar to attribute a result to a for
statement (as statements generally do not yield results), they can produce an outcome within the context of the entire program execution. This outcome can be accessed by the environment running your code.
For instance, you can achieve similar results using the eval()
function, which provides the final statement's result.
var n = eval('for(var i = 0; i < 3; i++) {i}');
console.log(n);
In this case, you will see 2
in the console as the evaluated result of the program, even though the sole outcome results from the for
loop returning the final statement result of its last iteration.