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

Mahfuzur Rahman
Mahfuzur Rahman
3,204 Points

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

I understand what div is. But in the for loop how is the variable html changing? first html was an empty string. I don't understand how are we putting the values of 1 to 10 in it.

from my understanding variable html becomes == html+<div>+1 </div>== (when i=1)

+=

is for concatenation

 var a = "fuzz";
 a += "y";       // a -> "fuzzy"

=

is for assignment

 var a = "fuzz";
 a = "y";       // a -> "y"

1 Answer

Matthew Long
Matthew Long
28,407 Points

You can always write out what a loop would be every time it runs.

var html = "";

for (var i = 0; i <= 10; i += 1) {
  html += "<div>" + i + "</div>";
}

When the above loop runs the first time the html is:

<div>1</div>

After it is run 10 times the html is:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>

The reason it is a new <div> each time the loop is run is due to the += operator. It if was simply = then the html would be the following after being looped over 10 times:

<div>10</div>

Hopefully this clears things up for you.

Nicholas Wallen
Nicholas Wallen
12,278 Points

That does help, A LOT.

Honestly, this was a very poorly taught video.