Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Introduction to Programming Control Structures Loops

Adam Ocasio
Adam Ocasio
1,742 Points

Question 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

The 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
Kelly von Borstel
28,877 Points

counter++ 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