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

Code Challenge: Refactor Using a Loop

The question asks to do the following:

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.


My code is posted below.

Any help is appreciated.


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

6 Answers

Two things

  1. You don't have to use var in a loop definition
  2. The third portion of your loop declaration needs to increment i - you need to INCREASE the value of i - the code you have written is not actually increasing i - it just returns the same number every time

This gave me trouble also. I went back in my notes to the first lesson on for loops and found the answer. The correct code is...

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

I don't want to give you the entire answer, but my suggestion is to reread what the output should be and then take a look at what your function will output. The answer should become apparent.

Well, I changed it to:

for (var i = 2; i <= 24; i + 2) {

And it killed Google when I tried running it in the console; so, is there something wrong with the < = 24 ? But I thought that part of the code told it to run until i < = 24 (meaning that, once i > 24, the code would stop).

i + 2 is missing something.

I got it to work. I forget exactly the code I used; I think I changed 2 to a 1, but I was using i + number when I should have been using i += number. Once I changed it to +=, it worked!


thats the wrong answer

Caden Ingram
Caden Ingram
6,482 Points

No it's not, he was clever enough to find that out.