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

What am I doing wrong?

Do I times my variable by 2 to get the even-only numbers?

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

2 Answers

Hi Eric,

First off, you're likely getting a a parse error since you used the while keyword. You likely meant to do a for loop.

In the for loop, i can be initialized to whatever number you want. It doesn't have to start at 1. So in this case, you can check the existing log statements and see that it starts at 2.

You have to go up to and including 24 so you have your conditional part correct.

The next thing is that you're incrementing by 1 but you can increase or decrease the value of i by any amount that you want so you can do what is convenient for this problem. To go from one even number to the next one, you have to add 2.

Now you've got the for loop generating the exact values that you need and there's no need to do any calculation inside your console.log statement.

Trevor Johnson
Trevor Johnson
14,427 Points

Hey Eric, I would solve this by starting i at 0 and increasing i by 2 on each loop and then console.log(i) each time through. That will print every even number.

Thank you