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 trialnick88p
5,716 PointsFor loop - Code took too long to run
This code took too long to run (my initial answer): for (var i=4; i=156; i++) { console.log(i); }
This code was accepted: for (var i=4; i<=156; i++) { console.log(i); }
The only difference between the two is that I changed i=156 to i<=156. Can anyone tell me why I can't use merely "=" ? The result should be the same if you think about it logically ... shouldn't it?
Thanks, Nick
2 Answers
Ryan Field
Courses Plus Student 21,242 PointsHey, Nick. What's happening here is that you are using a single equals sign in the second statement instead of a comparison operator (==
or ===
). When you do this, you are setting the value of i
to 156
and doing this in a while statement will produce true
, effectively making the for loop go on forever.
If you want to have the loop cycle up until 156, then you can use the less-than-or-equal-to operator, like this:
for (var i=4; i<=156; i++) {
console.log(i);
}
nick88p
5,716 PointsGot it. Thanks for the quick response, Ryan!
nick88p
5,716 Pointsnick88p
5,716 PointsI am not sure why this is not displaying correctly when I post the code. It just cuts off half of my sentence, even though I see the full sentence when I edit the question ...
The only difference between the two is that I changed i is equal to 156 to i is equal to or smaller than 156.