Sample Question - Whats wrong with my for loop?


#1

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…

i+1

…does anyone have any hints or suggestions?


#2

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


#3

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


#4

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!")
}

:ninja:


#5

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


#6

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?


#7

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 )