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 trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Refactor Using a Loop

Hey ! The error message tells me I have an undefined number in the log... what's wrong with my code ?

I can't seem to figure out what's wrong with this one.

script.js
for (var i= 1; i<=24 && ((i%2) == 0); i++) {
  console.log(i);
}
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

for (var i= 1; i<=24; i++) { console.log(i); }

Give that a try, let me know if it works : )

4 Answers

Bill Walker
Bill Walker
5,951 Points

Not 100% sure if this is relevant to the error you're receiving, but your for loop would exit right away. Your variable i starts at 1, so the second part of your statement would evaluate as false. Since you're using &&, the whole statement is false and your loop would exit immediately.

Seth Kroger
Seth Kroger
56,413 Points

The challenge is asking you to log the even numbers from 2 to 24 using a loop. Let's step through what your loop is doing:

The initialize statement is: int i = 1; so i = 1 at the start.

The condition statement is i>=24 && ((i%2) == 0); or loop until i is greater than 24 or i isn't even. A for loop, just like a while loop will check the condition before running the inside of the loop. Because i is already odd at the start, the loop will never run.

The step statement is i++ which increments i by 1 each loop. Even if you started with 2, the next time through the loop i would be odd again, and the loop ends.

(A for loop doesn't have to always start at 1, and doesn't have to increment by only 1)

Thanks for the help guys, I think I shouldn't post questions at the end of the day, this one was an easy one and I feel stupid to not having figured it out immediately...

Hey Charlie! I'm glad you were able to accomplish what you needed. Feel free to ask questions (I hope this isn't like overstack) - this is how we learn. It's good to have a supportive community and I hope this forum isn't run like others (where questions are bashed). Happy coding, change the world.