Javascript: When Writing A For Loop, Why Does It Print The Last Index Number?
When writing a simple for loop in the js interpreter, I automatically get the last value the index number (i, in this case). js> for (var i=0; i<100; ++i) { numbers[i]=i+1; }
Solution 1:
All statements in javascript have a value, including the block executed in looping constructs. Once the loop block is executed, the final value is returned (or undefined
if no operations take place). The statement that is implicitly providing the return value "100" is numbers[i] = i+1;
, as the final iteration of i+1 produces 100 and assignment operations return the value being assigned.
console.log(hello = "World"); // outputs 'World'
Now, this is not to say that you can assign the result of a for loop to a variable, but the interpreter "sees" the return value and prints it to the console for you.
I will also add that it is the result of running eval
on your code:
eval('numbers = []; for(var i = 0; i < 100; i++){ numbers[i] = i+1; }')
Post a Comment for "Javascript: When Writing A For Loop, Why Does It Print The Last Index Number?"