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

very simple but i can't solve [Refactor 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.

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

Vladut Astalos
Vladut Astalos
11,246 Points

You can check for every i from 2 to 24 if the remainder of dividing i by 2 is equals to 0, if it does that means that i is an even number. You can do that with '%' operator which returns the remainder of a division.

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

Or you can simply increase i in your loop by 2 instead of 1

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

thanks so much Vladut for the help and explaination. its now clear to me now. my brain is very slow. Can i follow you in twitter? :)

Vladut Astalos
Vladut Astalos
11,246 Points

You're welcome, I'm so glad I could help! If you want to follow me on twitter you can find me @AstVLD

Steven Ang
Steven Ang
41,749 Points

You're told to print all even numbers below 24. First off, we declare a for loop. Then, we declare a variable called i and assign a value of 2, this variable will be the counter and give a condition for the loop to run, in this case, print the value below or equal to 24. Then, increment it by 2 and inside the loop, log the value to the console. The values will be the same as the redundant code as before.

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

If your question is answered, please consider selecting any answer that satisfies you as a "Best Answer". This indicates that your question has been answered and can prevent unnecessary posts. Have a nice day and happy coding!

thanks so much Steven for the help and explaination. its now clear to me now. my brain is very slow. Can i follow you in twitter? :)