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 trialBo Kooser
2,418 PointsJavaScript Loops, Arrays and Objects
Hi! How can I fix the code so i as the numbers are shown in the console in separated lines? :)
var html = '';
for (var i = 2; i <= 24; i += 2) {
html += i ;
}
console.log(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
15,369 PointsBo,
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
2,418 PointsThank you very much for your help! :)