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 trialdotz
6,733 Pointswhy use += for adding html?
I tried this code replacing += with + (which is what i thought it would be!) and it did not run. Can someone explain why += is used here?
var html = ' ';
for(var i = 1; i <= 10; i +=1) {
html += '<div>' + i + '</div>';
}
document.write(html);
Thank you
1 Answer
David Diehr
16,457 Points(First off, I'm a beginner too so I may be wrong) I would say that it wouldn't run, because without an "=" then what is that line of code doing? You're just adding a variable to a string to a div. But you're not saying what to do with those added values. The "=" is telling the program to use those added (concatenated, actually) values to set a new value for the html variable. The code uses "+=" in order to add the new values to the existing html value. Which is why the html value that is written in the end includes all the divs.
William Li
Courses Plus Student 26,868 PointsWilliam Li
Courses Plus Student 26,868 PointsDavid, this is a great answer.
Let me add that, for beginner, the syntax of this code
i +=1
may look kinda strange. But in the nutshell.You ask the computer to compute
i + 1
, and assign the result back to i. This is how you increment the value of i by 1. And since when writing JavaScript, it's so common to increment a variable by 1, the language gives you a shorthand way of writing iti += 1
.