DEV Community

Discussion on: Why Does JavaScript Do THIS? - Question #1

Collapse
 
goncalodcorreia profile image
Gonçalo Correia • Edited

The way I see it you are constantly overwriting that value. For each item in the array you are assigning it to the same variable. By adding the += you are basically saying “hey add this value to my variable” instead of “hey assign this value to my variable”.

Assigning something means no matter what you had there before, it will now point to the new value you chose (this is achieved by using = ). The += is instead looking at what you have there and adds your new value to that, concatenating it.

I know it’s not a very technical explanation but I hope it does help.

Collapse
 
novajay2415 profile image
NovaJay2415

Thank you so much! Your reply helped me a bunch. And I am also grateful for the non-technical explanation. I have a hard time understanding when the reply is too "techy" so thank you! I really appreciate it.

Collapse
 
goncalodcorreia profile image
Gonçalo Correia

No problem, glad i could help 😁

Collapse
 
terabytetiger profile image
Tyler V. (he/him)

👆 Exactly this.

= replaces what is currently in innerHTML
+= appends more information to innerHTML

Breaking this down a bit further:

listOfNames.innerHTML += `<li>${name}</li>`

is shorthand for:

listOfNames.innerHTML = listOfNames.innerHTML + `<li>${name}</li>`

So whenever you call the += line, you're adding an <li> to your existing innerHTML instead of replacing it (which is the case with =)