0

I have some trouble understanding what happens during this for loop. I can imagine the function cycles, as in the value of "text" is changed five times. But when I imagine how it works, shouldn't the output of this whole block of code be 9? Because first, "text" changed its value five times, ending at 9, and then the document. part was executed. But the output is 1 3 5 7 9. Can someone explain what really happens?

var text = "";
var i;

for (i = 1; i < 10; i = i + 2) {
    text += i + "<br>";
}

document.getElementById("demo").innerHTML = text;
Joe Doe
  • 171
  • 1
  • 3

1 Answers1

0

This is called shorthand assignment operators.

Addition assignment operator(+=): Usage: a+= b is equivalent to a=a+b
Subtraction assignment operator(-=): Usage: a-=b is equivalent to a=a-b

var text = ""; var i;

for (i = 1; i < 10; i = i + 2) {
    text += i + "<br>";  // is equal too text = test + i + "<br>";
}

document.getElementById("demo").innerHTML = text;

To add to my answer .

Text is a string and in JavaScript if you do addition in the text variable its called concatination .

What here happening is this .

Every time loop run . It concat the pervious text value and i to the text variable.

Text += i "
";

Every time append new value to the same text variable.

For example. First time loop run it set 1 in 'text' variable and then again it iterate 3 is append to the perivous 'text' variable .So every time loop runs the i value ia append to 'text' .

Himanshu sharma
  • 5,735
  • 4
  • 36
  • 58