-2

I'm having trouble understanding why this for loop is text += cars[i]... and not just text = cars [i]...

Here is the full script

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

document.getElementById("demo").innerHTML = text;
<p id="demo"></p>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
TKW
  • 27
  • 4
  • 4
    Try it and find out. If it was `text = ...`, then `text` would only reflect the final iteration. – CertainPerformance Aug 02 '18 at 01:07
  • not sure which part of `+=` confuses you ... `text += cars` .... is `text = text + cars` ... and `'string1' + 'string2'` results in `string1string2` - – Jaromanda X Aug 02 '18 at 01:11
  • Do you know what `+=` does? – jhpratt Aug 02 '18 at 01:12
  • @JaromandaX, believe you have best comment. Consider making it an answer so can be accepted? – asantaballa Aug 02 '18 at 01:16
  • @asantaballa - I don't believe in posting answers for what I consider to be `Javascript 101` type questions - a javascript programmer should know what `+=` is within the first hour of their javascript programming journey :p – Jaromanda X Aug 02 '18 at 01:19
  • @JaromandaX, understand and hope did not offend. Just see many people lose credit when without realizing it when they in fact answered the question. Thanks for response. – asantaballa Aug 02 '18 at 01:22

3 Answers3

1

= is assignment

+= is assignment and addition


so if text += 'abc'

and text was initially def,

the result will be defabc


in your case, the result would be

BMW<br/>Volvo</br>Saab<br/>Ford<br/>

kkesley
  • 3,258
  • 1
  • 28
  • 55
0

The += operator, such as: x += y, is the same thing as writing x = x + y. In your example, each item in the cars array is being added to a new variable, text, with a 'br' tag inserted between them. It should list all of the cars listed in your array one above the other. If you just used the = operator, the 'text' variable would be overwritten several times until the loop ends, thus you would just see the entry 'Ford' as it's the last in the array.

Dean
  • 1
  • 1
0

using += the output is BMW Volvo Saab Ford

So basically since its a for loop , on each iteration the value of text is built as BMW
Volvo
Saab
Ford

If you remove the + from the script on each iteration the value of text will be replaced by the car[i] and the end value of the variable text will be Ford