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 trialYixi Guan
7,927 PointsHave hard time to understand html += ...
It's easier to understand it if the code is as below:
var html = '';
for ( var i = 1; i <= 10; i += 1 ){
html = "<div>" + i + "</div>";
document.write(html);
}
How to understand the other way? If "html += i" means "html = html + i", the second time runs the loop it will be "html = 1 + 1", third time will be "html = 2 + 2", because "html" equals "2" and "i" equals "2" after runing it two times?
var html = '';
for ( var i = 1; i <= 10; i += 1 ){
html += "<div>" + i + "</div>";
}
document.write(html);
4 Answers
Casey Ydenberg
15,622 PointsHi Yixi,
I think you're overthinking it. += just takes the existing html
and plops everything to the right onto it.
So before the loop runs html
is an empty sting.
After the first loop it is
<div>1</div>
After the second loop it is
<div>1</div><div>2</div>
Hope that helps.
Fidel Severino
3,514 PointsYixi,
I actually paused the video before he showed his solution and did it just the way you had it in your first code block. I too think that is a simpler way to do it that looks less confusing.
After I saw how he completed the exercise (your second code block above), it took me a few seconds to understand how it would work. Just think after the loop has finished, html
simply becomes a variable holding a bunch of divs with numbers.
html = '<div>1</div><div>2</div><div>3</div>...'
<!-- and so on up to the number set in the condition for the loop -->
Casey Ydenberg
15,622 PointsThe disadvantage of Yixi's first code block is that you wouldn't be able to wrap it in a function that returns html
. Other than that, it would have exactly the same effect.
Yixi Guan
7,927 PointsI think I know what you mean now. Didn't have a clear understanding of "+=". Thanks.
Yixi Guan
7,927 PointsThank you Julie, you solved my confusion. I agree with everybody, compare with my way, html += has more advantage. I just need to get used to using it. Thank you all.
Julie Myers
7,627 PointsJulie Myers
7,627 PointsDepending on what it is applied to, the + operator will either perform addition or concatenate two or more things together. The = operator only does one thing, it assigns a value to a variable.