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);
+= 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)