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

Trying to create a loop of only even numbers from 2 - 24.

Here’s what I’m asked:

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.

Here’s My Code:

var i=2;

while (i<=25) //Output the values from 0 to 10 { console.log(i + "<br>") i+2; }

script.js
var i=2;

while (i<=25) //Output the values from 0 to 10
{
  console.log(i + "<br>")
  i+2;
}
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,735 Points

First of all, don't worry about adding any html here ("<br>"), you're not putting content onto the page in html, you're printing to the console - the one you can view in the Chrome Developer Tools but that regular users don't see.

There's also a much easier way of selecting only even numbers using the modulus (%) operator. It gives you the remainder, so any number modulus 2 with a remainder of 0 is an even number. You can do it like this:

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

I'm using a 'for' loop instead of a while loop. Not sure if that's inline with what this section was teaching, sorry if I'm confusing you.

It worked like a charm. Thanks Brendan. It worked for now, but I think I'll take a moment to study how it really working. I feel so dumb transitioning from HTML to JS.