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 trialMarwan Bakr
7,579 PointsWhat's wrong with this code?
What's wrong here?
for (var i = 2; i<25 && i % 2 == 0; i++) {
console.log(i);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
2 Answers
Tijo Thomas
9,737 PointsThe third statement in your for loop iterates i by one. Your code block executes and logs 2 to the console, but fails after that since i now becomes 3 (fails i % 2 == 0). Changing the third statement what's listed below would work.
i += 2
A better way to do this so you are not testing two conditions is:
// i gets increased by 2 every time through the loop and once it becomes 26 the loop will end.
for(var i = 2; i < 25; i += 2) {
console.log(i);
}
Jennifer Nordell
Treehouse TeacherHi there! You're pretty close here, but the setup for your for loop is incorrect. Remember that the middle section defines a range. When that condition first evaluates to false, the loop exits. You have as your range:
i < 25 && i % 2 == 0
Because the variable i starts with a value of 2, during the first iteration 2 is less than 25 and 2 is evenly divisible by 2. So the console.log executes and logs out the value 2. Then we increment 2 to 3. And here's where it fails. The value 3 is less than 2 but 3 is not evenly divisible by 2. Thus, the expression fails and the for loop exits.
Here's your hint: make the check for i
being divisible by 2 inside the for loop with an if statement. If it evaluates to true, execute the console.log.
I believe you can get it with these hints, but let me know if you're still stuck!
Jennifer Nordell
Treehouse TeacherTijo Thomas makes an excellent point! You can just increment by 2 instead of doing the if statement I suggested. Either method will work!