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 Create a for Loop

Camille Foor
Camille Foor
6,956 Points

Creating a for loop.

Can someone point out what I'm missing in this code?

script.js
var html = '';

for ( var i = 4; i<=156; i += 1 ) {
    html += '<div>' + i + '</div>';
}

console.log(html);

1 Answer

This task is a little weird. Your code is technically correct and will print 1,2,3,4,5,6...150,151,152,153,154,155,156, but the code challenge wants your for loop's condition to be "i < 156", which prints 1 to 155. It's a little weird!

Also, there's no need to use the var keyword when making a variable for a for loop. You code will still work with it, it's just best practice to not. Finally, you said "i += 1", which is 100% OK, but most of the time people use "i++" which is like the shorthand way. It isn't required to change "i += 1" to "i++" for this challenge. It's just a thing you'll see in other code :)

Also, this step is required, the challenge asked you to console.log() the number, not to add it to a html variable. You should get rid of the html variable completely and put the console.log inside of the loop. The code should look like this:

for ( i = 4; i < 156; i++ ) {
    console.log(i);
}

Good luck! :)

Hope this helps, Alex

No problem! Can you please give me a best answer so that this question won't be in the Unanswered questions section of the Community? :)

Thank you! ~Alex