Search code examples
javascripthtmlfor-loopgetelementbyidinserthtml

Getting started with javascript, got a questions


I'm following w3school beginner tutorial for JS. There's something I don't understand from code below:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var cars = ["Saab","Volvo","BMW"];
var text = "";
for(var i = 0; i < cars.length; i++) {
text+=cars[i] + "<br>";
}


document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Can someone explain me the logic of text+=cars[i]? I understand that += means increment, but I can´t understand the logic behind adding the array element to variable text.

Thank you so much for your quick replies! I've got a follow up question: is there an alternative to display the same type of information with having to use the

var text = "";

and

text+=cars[i]

pieces of code? If so, how would the snippet of code look like and what should I insert into HTML if not

text

?

Thanks again!


Solution

  • a+=b is short for a=a+b. In your case you have text = text + cars[i] + "<br>".

    text is a string, and you are using + to append a value from the array (that contains strings), and then append "<br>"