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

Daniel Baker
Daniel Baker
15,352 Points

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! :)