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

cant figure out why this wont work....

please help

script.js
for ( i = 2; i <= 24; i + 2; ) {
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>

question is... 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.

5 Answers

What you have done is infinity loop with error in statement:

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

First of all, there must be only two ";" instead of yours three. The last one break your code.

The second is incremental "step statement ". It should be "i +=2" or "i = i + 2". Your expression will not change "i" variable and the loop become infinity.

Third - where did you define "i" var?

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

Now it will work!

Jennifer Crawshaw
Jennifer Crawshaw
17,878 Points

It looks like you just have a syntax error! You don't need the semicolon after the i + 2 statement, and you can write that as i += 2

That should work!

Thank you Daniel! And thank you for some explanation as to why I was wrong!

i had to use a while loop

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

var j = 'evenNumber';
for ( var j = 2; j <= 24; j += 2 ) {
  console.log( j );
}

MAKE SURE YOU 'CONSOLE.LOG' j