Reputation: 33
According to Mozilla, the Addition Assignment operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition. Here's the behavior of the addition:
Basically, text+=i
is the same as text = text + i
; that is a fact.
Ok, if the above is true, then why in Code Version 2 below when I variable-ize the string "The number is "
to the variable text
,
doesn't it write the string each time with the new number as code version 1 does?
And for the answer I don't want another way to write it. I need to figure out why it doesn't work the same way if text+=i
is the same as text = text + i
.
I'm getting better at JavaScript every day, but believe it or not this simple +=
is holding me back from further understanding it because too many examples are using +=
.
Here is the Code Version 1:
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
Here is the Code Version 2 with var text
variable-ized with the string "The number is "
:
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text ="The number is ";
var i;
for (i = 0; i < 5; i++) {
text = text + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
Upvotes: 0
Views: 148
Reputation: 9782
For a question like this, it can be very helpful to use console.log to see what is happening.
var text ="";
var i;
console.log("First approach");
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
console.log("Iteration: "+i+" Text: "+text);
}
console.log("Second approach");
text ="The number is ";
for (i = 0; i < 5; i++) {
text = text + i + "<br>";
console.log("Iteration: "+i+" Text: "+text);
}
The code runs differently because in the first case you concatenate the entire string of "The number is ..." and in the second case, you initialize the string with "The number is " and then only concatenate the digits.
Upvotes: 1
Reputation: 14423
You are writing different code.
a = a + b
is indeed the same as a += b
.
var text = "";
text += "The number is " + i + "<br>";
Is the same as:
var text = "";
text = text + "The number is " + i + "<br>";
But it's not the same as:
var text = "The number is ";
text = text + i + "<br>";
Which is what you had.
Upvotes: 3