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

Re-write this using a loop

The code below logs all of the even numbers from 2 to 24 to the JavaScript console. However, there's a lot of redundant code here. Re-write this using a loop.

Here is what I came up with...

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

I keep getting the error: Bummer! There was an error with your code: SyntaxError: Parse error.

Any ideas what I've done wrong.

2 Answers

Hey Callum,

Take a look at your conditional. You're saying the loop should run as long as i is equal to or less than 24, which is not how conditional logic works in JavaScript. In short, it's backwards. You should first check if i is less than 24 and then if it's equal to 24. You'll also want to watch how you add to your i variable. i + 2 is not the same as i += 2, which is what you want in this case.

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

Your post logic action needs the equals (=) symbol to indicate you are adding 2 to i each time the loop runs - otherwise your loop can't progress.

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

:)