Search code examples
javascriptdomdocument.write

Javascript "document.write" confusion


I'm new to JavaScript and may have asked a dumb question.. But the result returned from below code made me so confused. I'm not sure why only the first sentence show the value of i and it was in the last number of 3.

I'm also confused when the code document.write('<h1>' + i + msg + '<h1>') being executed, why it didn't just write the aggregated value of the variable 'msg'? The value of msg didn't get wiped out and it should contain both the 1st and 2nd value passed into it isn't it? This looks a bit confusing to me as I came with some python knowledge and it didn't work in the same way.

var scores = [24, 32, 47];
var scores = [24, 32, 47];
var scores = [24, 32, 47];

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.write('<h1>' + i + msg + '<h1>')

Result returned from the html:

3 Round 1: 24 
Round 2: 32 
Round 3: 47

My expected result:

0 Round 1: 24
1 Round 2: 32
2 Round 3: 47

Solution

  • document.write runs after the end of the loop.

    It does output all the aggregated content of msg. That isn't the issue.

    The bit that's going wrong is the use of i - you only use it once in the output, after the loop ends. Therefore what you see will only have the final value it had when the loop ended, hence it shows 3, and does so once only.

    Unlike msg which you are adding to each time the loop runs (because += appends new content to the existing variable), the value of i is overwritten with a new value each time the loop runs (that's what the i++ in the for syntax does).

    To make it do what you want you simply need to incorporate the i value into msg as you go along instead.

    var scores = [24, 32, 47];
    var msg = '';
    
    for (let i = 0; i < scores.length; i++) {
      msg += i + ' Round ' + (i+1) + ': ' + scores[i] + '<br>';
    }
    
    document.write('<h1>' + msg + '<h1>')

    P.S. I also simplified the code slightly - it's unclear why you declared the same scores array 3 times with the same value, and arrayLength and roundNumber don't need to exist as separate variables, and certainly not ones which have scope outside the loop. i also doesn't need scope outside the loop anymore.