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 trialAdam Gheli
3,714 PointsTrying 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; }
var i=2;
while (i<=25) //Output the values from 0 to 10
{
console.log(i + "<br>")
i+2;
}
<!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
Front End Web Development Techdegree Graduate 84,738 PointsFirst 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.
Adam Gheli
3,714 PointsAdam Gheli
3,714 PointsIt 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.