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

Jonny Strange
Jonny Strange
6,412 Points

Javascript help??

I'm a bit stuck on this question. I suppose to out the even number 2 to 24, but I can help??

script.js
for (var i = 0; i <= 11; i += 1) {
  console.log(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

Erik McClintock
Erik McClintock
45,783 Points

Jonny,

You're close here, it's just a matter of watching what you do with your variable 'i', and how long you allow the loop to run. But, you have the correct syntax, which is great!

If you need to print every EVEN number between 2 and 24, there are a couple of things we need to change in your condition.

1) The value of 'i' might as well start at 2, since that is where you want to begin logging it to the console.

2) You will want to make your condition run until 'i' is equal to 24, so change your 11 to 24.

3) Since we want to log every even number and we're not obligated to do anything with the uneven numbers, we can just increase the value of 'i' by 2 every time so we're only even ever bothering to look at the even numbers!

So, the end result would be:

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

Open up your developer tools, go to the Console tab, copy and paste that code snippet in, and you'll see what you're looking for :)

Happy coding!

Erik

I've used a radically different approach, but for some reason it doesn't work inside the code challenge window. It works fine though in workspaces. Any comments?

for ( var i=2; i<= 24; i++ ) {
  var counter;
  counter = i / 2;
  if ( Number.isInteger(counter) ) {
  document.write(i +'<br>');
  }
}