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 Tracking Multiple Items with Arrays Using For Loops with Arrays

Tibor Ruzinyi
Tibor Ruzinyi
17,968 Points

For loops with arrays question : += vs. +

Hello,

Is there a specific reason to use in Daves code :

listHtml += '</ol>';

instead:

listHtml + '</ol>';
Stephen Little
Stephen Little
8,312 Points

Don't know much about JavaScript but isn't the first one assigning the value of listHtml the value of listHtml + the order list ending.

So this

listHtml +='</ol>';

would give you what ever value was in the listHtml var and add the order list end tag to the end of it.

Just what I saw at first glance... cheers! Stpehen

2 Answers

Sean T. Unwin
Sean T. Unwin
28,690 Points

+= is a shortcut to say 'this equals this plus whatever comes next'.

In terms of Strings, it will concatenate (or attach to) the existing String with the String that is presented after the +=.

When dealing with Numbers, this will add the Number following += to the existing Number. It is also possible to use -= on Numbers as well where this will subtract the Number after -= from the Number before the -=.

/* STRINGS */
listHtml += '</ol>';

/* is the same as */

listHtml = listHtml + '</ol>';

/* is the same as */

listHtml.concat('</ol>');
/* NUMBERS */
var a = 3;
var b = 7;

/*   +=   */
a += b; // 'a' is now 10;

/* is the same as */

a = a + b;

/*   -=   */
b -= a; // 'b' is now 4 (using original variable values)

/* is the same as */

b = b - a;
Tibor Ruzinyi
Tibor Ruzinyi
17,968 Points

Thank you very much for your answer, But why just not use listHtml + something. If i use this i will get the same output.

Sean T. Unwin
Sean T. Unwin
28,690 Points

It saves having to type listHtml out twice, i.e. listHtml = listHtml + something;.