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

Rachel Hutchings
Rachel Hutchings
4,293 Points

I am getting an error saying "I did not log the even numbers between 2 - 24" Though according to my code I should be?

The challenge is to log only the even numbers between 2 and 24. I am simplifying the code by placing it in a loop. This is what I have -

var evenNumber;

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

I am either getting errors that it is logging 11 or 13 times instead of 12 (what it needs to be) or that it is not logging the even numbers between 2 and 24. No matter how much I tweak I can't get it to work. What am I missing? I tried making the var i = 2 and i <26 or i = 0 and i <= 24 but nothing seems to work! Help!

script.js
var evenNumber;

for (var i = 0; i < 24; i += 2) {
  console.log(evenNumber);
}
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

Raphaël Seguin
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Raphaël Seguin
Full Stack JavaScript Techdegree Graduate 29,228 Points

Hi, there are two problems in your code. You need to change the value of your variable before you use it, and you should start at 2 and not 0. You can use this var in the for loop and then make it increment by two so you get only the even values, like this :

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

I hope it helps.

Rachel Hutchings
Rachel Hutchings
4,293 Points

Thanks so much! This solved it :) I had a feeling I was getting something mixed up with the vars. Thank you!

Mike Henry
PLUS
Mike Henry
Courses Plus Student 5,373 Points

You're close. You we're right to start the loop at i=2 and then you should end it at i<= 24 so it will include 24 and then just console.log the variable i or if you want to use the variable evenNumber you need to assign i to it (evenNumber = i) inside the loop. This is what I used: for (i=2;i<=24;i+=2){ console.log(i); }

Rachel Hutchings
Rachel Hutchings
4,293 Points

Thanks, Mike! This was really helpful :)