Reputation: 87
I'm currently studying javascript on my own and would like to see if anyone could help me clarify this questions I have. I'm currently learning loops and came across this code in the book:
var scores = [34, 45, 66, 1023, 1030, 'Done!'];
var arrayLength = scores.length;
var roundNumber = 0;
var msg = '';
var i;
for (i = 0; i < arrayLength; i++) {
roundNumber = (i + 1);
msg += 'Round ' + roundNumber + ': ';
msg += scores[i] + '<br />';
}
document.getElementById('answer').innerHTML = msg;
<div id="answer"></div>
Now that loops through the array and returns all numbers in the array. But If i were to change:
var msg = ''; to var msg;
msg = 'Round ' + roundNumber + ': ';
it only returns the last item in the array. Why does that affect it? How does making the msg variable as null change everything?
Upvotes: 1
Views: 93
Reputation: 36
The issue is at the following line:
msg = 'Round ' + roundNumber + ': ';
The line should actually read:
msg += 'Round ' + roundNumber + ': ';
Upvotes: 0
Reputation: 16821
There are two things here you must understand:
=
It is an assignment operator. The operation var x = 'something'
means that any value inside x
will be forgotten, and replaced by the new value 'something'
.
+=
It is a binary operator. It increments the value of a variable, so x += 'something'
will add the value 'something'
to whatever value was already inside the x
variable. It's the same as x = x + 'something'
So, don't initializing a value for the variable, would just make it not having anything to add to:
var msg;
msg += 'Round' //This would give you 'undefinedRound'
Now, in your case, you removed the +
sign, so you used a simple assign operator =
. Every time the for loops, it will reset the variable's value.
Upvotes: 2
Reputation: 121
msg += 'Round ' + roundNumber + ': '; //update the msg by adding previus value plus current value
msg = 'Round ' + roundNumber + ': '; //update the msg by adding only the current value. Just like assigning new value in the msg variable.
Upvotes: 1
Reputation: 556
Making the following declaration
var msg;
DOES make msg == undefined
initially, but the problem is that second line you changed:
msg = 'Round ' + roundNumber + ': ';
This causes msg to be equal to ONLY THAT value on the right side of the value assignment. By using +=
rather than just =
, you are continuously concatenating onto previous values of msg
.
Upvotes: 2