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 For Loops

Leno Marin
PLUS
Leno Marin
Courses Plus Student 1,323 Points

Why the "html+= "

In this code: var html = '';

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

document.write(html);

Why does the html declaration inside of the for loop block need to be written as such :html = html + '<div>' + i + '</div>'; }.

Versus just: html = '<div>' + i + '</div>'; ?

2 Answers

html = html + '<div>' + i + '</div>';

This code assigns whatever was in html variable before and adds div with i inside. If you use this:

html = '<div>' + i + '</div>';

It will reassign variable's value, so each time this assignment is done you will lose previous value stored in html. That's why you need to use first snippet or if you prefer shorthand you may use:

html += '<div>' + i + '</div>';

Operator += does the same thing as writing html = html + '<div>' + i + '</div>';

Can anyone make it clear why this var HTML is written is the first place??? I don't get the point