Question

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; }
100
js> i
100

Can someone please explain why the interpreter works like that? I didn't explicitly ask it to print the value of i.

Sorry for the ambiguous formulation, guys, but I didn't really know how to describe what's happening.

Was it helpful?

Solution

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; }')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top