0
var fruits = ["Apple", "Mango", "Guava", "Grapes", "Peach", "Pineapple"];
var i, txt;
i = 0;
txt = "";
for (; i < fruits.length; i++) {
    txt = fruits[i] + "<Br>";
}
document.getElementById("demo").innerHTML = txt;

In the code above, why the for loop returns only the last value (Pineapple) from an array and why we should use "txt += fruits " instead of "txt = fruits" sign to get all the array values.

  • 2
    Because assignment (with `=`) *overwrites* the existing data, whereas `+=` is string *concatenation*. – costaparas Jan 16 '21 at 03:53
  • 1
    Programmers go to great lengths to not say the same thing twice. They try hard to avoid repeating themselves. – danh Jan 16 '21 at 03:57

3 Answers3

2

TL;DR

+= appends the value, so the values continuously add up. = overwrites.


+= indicates adding the current value of the variable, along with the new value on the right hand side of the argument. a+=b is simply a=a+b, which helps make code more succinct.

Inside the loop, you are continuously setting txt to the current value. Eventually, the last cycle of the loop is on the last item of the array, therefore txt is the last value.

You can think of it this way:

Inside the loop, you set the variable to the current item. You first go to the first one, and the variable is set to the first one. You go to the second item, and the variable is set to the second item. Eventually, you go to the last item, and the variable is set to the last item.

If you use +=, you can think of it this way:

Inside the loop, you add the new item to what the variable already was. You first go to the first one, and you add the first item to "". You go to the second one, and you add the second one to the first one etc,. Once you reach the last item, you have added the second last, third last all the way to the first.

Spectric
  • 5,761
  • 2
  • 6
  • 27
1

It will overwrite all your txt fille to fruit[i], so your txt will end with fruits[fruits.length]. in your case you want to combine all your fruit array into string called txt that have all items in fruits separated by enter /

Ricky
  • 45
  • 5
-1

"+= " is like a=a+b we use instead a+=b