Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAdam Ocasio
1,742 PointsQuestion on why my loop is faulty
So I have a for loop that i was trying out for the extra credit and i don't understand why it turned into an infinite loop, could anyone explain this conundrum?
for (var counter = 0; counter <= 100; counter = counter++) { console.log(counter); }
when i run the above code it runs infinitely, but if I change the "counter++" to "counter + 1" it will print out numbers 1 - 100 as intended. Aren't the two commands the same?
2 Answers
Pierre-Emmanuel Turcotte
13,670 PointsThe problem is with your statement counter = counter++
in the for
evaluation.
What is happening is that the increment is happening after the assignment to the counter
variable. This is too late for the evaluation.
You can make ++
operator precede the variable to make the increment happen before the assignment. This will fix you code.
This works:
for(counter=0; counter<=100; counter = ++counter){
console.log("This works!");
}
Or you could just forget the assignment operator and just have the counter++
statement which would work as well:
for(counter=0; counter<=100; counter++){
console.log("This works!");
}
Kelly von Borstel
28,880 Pointscounter++ will increment counter -- it assigns the value to counter, so doesn't need the "counter =" to the left. These two statements are equivalent:
counter = counter + 1
counter++