Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Refactor Using a Loop

Carlos Fernández-Tejeda García
Carlos Fernández-Tejeda García
4,051 Points

Why I can not log out the even numbers from 2 to 24?

Hi all. I have to log out the even numbers from 2 to 24. I am trying the following code:

//assign i as loop counter, var i = 0; //* ej is used to add 2 to the initial value and add 2 to the set value everytime that the loop runs // var ej= 0; // until i gets the value 12, the variable sum is added + 2 every time that the loop runs and i increases one *// while (i < 12){ var sum = ej + 2; console.log(sum); i++ } But bummer says that I don´t log out the even numbers. What I am doing wrong?

Thanks

script.js
var i = 0;
var ej= 2;

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

3 Answers

Patrik Horváth
Patrik Horváth
11,085 Points

";" missing after i++ and you dont have compiler in JS so u cant see syntax error i recommended use PHP STORM or WEBSTORM its good for JavaScript witch have biuld in syntax check

AND your code will output only 4 then 4 then 4 then 4 look closer on it :) i mean line "var sum = ej + 2;"

and PS you dont need put META charset UTF-8 why ? cause its default value :)

Carlos Fernández-Tejeda García
Carlos Fernández-Tejeda García
4,051 Points

Thanks Patrik.

But the solution was easier than this, after having a thought I´ve got that

var i = 0; var ej= 0;

while (i < 12){ ej +=2; i+=1; console.log(ej);

} Cheers

Patrik Horváth
Patrik Horváth
11,085 Points

:) yup now ej increment by 2 every time :)

Tsenko Aleksiev
Tsenko Aleksiev
3,818 Points

Why not try to use "%" - when you devide two numbers, lets say 12 % 6 it gives back wats left of the devision in this case 0, if you try 13 % 6 the result is 1 or 2x6 = 12 and leftover 1. Start counting from 2, each iteration check if the var devided by 2 gives back 0 aka it's even number, than add +1 to the var, and check till the counter becomes 24. I would do it this way