-2

I am beginner trying to learn javascript from w3school, help to understand below code. if I remove + operator then I am getting only "Mango" in my output but why?

can any one explain using += operator if there is any similar examples please provide link if available with video explanation.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

let text = "<ul>";
for (let i = 0; i < fLen; i++) {
  text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

document.write(text);
James Z
  • 12,209
  • 10
  • 24
  • 44
  • 2
    `+=` appends while `=` just assigns. `x += y` is the same as `x = x + y`. If you use `=` instead of `+=` you would overwrite `text` in every iteration so only the last one (`Mango`) would stick. (Plus, you'd have an imbalance in your HTML tags.) – CherryDT Sep 24 '21 at 17:15
  • @CherryDT `+=` doesn't "append", it's a shorthand assignment, strings in JS are immutable. – Teemu Sep 24 '21 at 17:22
  • @Teemu From OP's perspective it's "Tomayto Tomahto" - in this context it does append. I don't think they are at _that_ point yet in their learning experience. – CherryDT Sep 24 '21 at 17:34
  • Should avoid using document.write() statements. Better to create element for display or send to console.log for testing – jmrker Sep 24 '21 at 17:49

1 Answers1

1

+= is basically used to append or add any two arguments (may be numbers or string) and then assign it to a variable

= is used to assign a value to a variable

example for += operator :


let text = ''; // an empty string

text += 'hello';

console.log(text); // output: hello ('' + 'hello', this is a string concat)

example with numbers

let number = 2;

number += 3;

console.log(number); // output: 5 (2 + 3, since it is a number it will add them)

another example with string


let text = 'hello i am';

text += ' John Doe';

console.log(text); // output : hello i am John Doe

Note

When using += on both a number and a string, it will treat the number as a string perform a concatenation

let value = 'hello';

value += 5;

console.log(value); // output : hello5 (this will be a string)
let value = 5;

value += 'hello';

console.log(value); // output : 5hello (this will also be a string)
AnanthDev
  • 1,605
  • 1
  • 4
  • 14