Sample Question - Whats wrong with my for loop?


This for loop seems to run an infinite loop, I wonder what’s wrong…

for(var i=0; i<10; i+1){
    console.log("To infinity and beyond!")

Something about the iteration expression that seems off to me…


…does anyone have any hints or suggestions?


Should be i++ or i=i+1… if you just set i+1 condtition, it will never iterate up to 10


Look at your third loop parameter–“i+1”. The result of an addition is almost always true.


Thanks @rmontgomery and @likejean, certainly not redefining the variable i will cause i to remain 0 forever and the loop will run forever. Thus we should make sure to redefine i in the iteration expression.

for(var i=0; i<10;  i=i+1  ){
    console.log("To - not quite infinity - and beyond!")



The reassignment i=i+1 can also be written as i++ as @likejean mentioned


Just curious, what happens with the stack memory allocation of the data type var i, while this loop is running forever. Initially, it stores zero in the stack memory at some location. If the loop updates this same registry iteratively up to 9, then it fails to execute the code after i=10… but what happens if if we have i+1? Does this registry updates at all?


Good question @likejean Sergey, var i = 0 sets the variable i to the value of 0 (keep in mind, numbers are primitive data types in JS), when we use the following code, we are not redefining i, the result of the code may be i+1 which is say 1 in the first iteration, but we never actually re-define the value of i to take on the new value, so i always remains a value of 0, we just take the value of i, add 1 to it and never use the result for anything.

var i = 0;
i // => 0
i + 1 // => 1 ( i is still 0 )
i = i + 1 // => 1 ( now i is changed to the value of 1 )