Hello Wonderful Dev.To Community,
I am doing my best to understand WHY JavaScript does WHAT it does. Sometimes I run into things I just can't wrap my mind around. This is one of these times...
My question is: Why does the last item in the array show up correctly, but all the other values are skipped over and not displayed, UNLESS I use "+="?
I am a JavaScript noob as you can probably tell from my question... But I would love to know WHY JavaSript is doing this. If you could let me know why that would help me a bunch. Thanks in advance.
Top comments (9)
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.
👆 Exactly this.
=
replaces what is currently ininnerHTML
+=
appends more information toinnerHTML
Breaking this down a bit further:
is shorthand for:
So whenever you call the
+=
line, you're adding an<li>
to your existinginnerHTML
instead of replacing it (which is the case with=
)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.
No problem, glad i could help 😁
Besides all the other explanations of the problem, you might not want to update the DOM on every single iteration of the array, as that probably isn't very efficient. Something that runs through the array first and updates the DOM later might be better:
Or, if you're not comfortable with
reduce
, simply:Your code is saying to use <li>${name}</li> for the listOfNames each time another name appears in the names array. If you were to slow down the result, you would see each name appear on top of the previous one. The += says to add it to whatever is already there. This way you will see them all next to each other.
Almost right
There are a couple of excellent answers. I just wanted to add that to achieve what you’re going for you may want to try .map instead of forEach.
Great question, though.
Override