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

Bo Kooser
Bo Kooser
2,418 Points

JavaScript Loops, Arrays and Objects

Hi! How can I fix the code so i as the numbers are shown in the console in separated lines? :)

script.js
var html = '';
for (var i = 2; i <= 24; i += 2) {

  html += i ;


}
console.log(html);
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

Bo,

Currently your console.log(html) will only be logged once because it is outside the loop.

To fix this put the console.log inside the loop.

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

But this will not get you your desired results.

Follow what is happening with your html variable and the i variable. first time round html will be 2, the second time around it is concatenating NOT SUMMING. This is because you made it a string when your first called it (var html = '';). The second time around it will be 24, third will be 246.

Instead you could have called the variable like this: (var html = 0;). But this still won't get you your desired results. You will be adding the index each time so it would log 2, 6, 12, 20.

For the answer, don't create another variable, but instead, log the i variable.

Answer below SPOILERS

for (var i = 2; i <= 24; i += 2) {
console.log(i);
}
Bo Kooser
Bo Kooser
2,418 Points

Thank you very much for your help! :)