Search code examples
javascriptloopswhile-loopinnerhtml

While loop and innerHTML - Why does it show the numbers in reverse?


function doItAgain() {

            var loopCount = 5;

            while(loopCount > 0) {

                    var target = document.getElementById("target");
                    target.innerHTML = "LoopCount: " + loopCount + "<br>" + target.innerHTML;
                    console.log("LoopCount is now: " + loopCount);
                    loopCount = loopCount -1;
                }

Here's the present function. It's activated by a button defined with the onclick event handler.

Now, my question is the following -> why does it show, once the button is pressed the numbers from 1 to 5 and not from 5 to 1 like in the console? I already know that if I set target.innerHTML to the start of the sentence that it will show them from 5 to 1 in my web page but I can't figure out why is that


Solution

  • Consider what this line does:

    target.innerHTML = "LoopCount: " + loopCount + "<br>" + target.innerHTML;
    

    Let's say that target.innerHTML, after the first loop, contains

    LoopCount: 5<br>
    

    Then on the loopCount = 4 loop, you're doing

    target.innerHTML = "LoopCount: " + loopCount + "<br>" + target.innerHTML;
    

    again, which is

    target.innerHTML = "LoopCount: " + loopCount + "<br>" + "LoopCount: 5<br>";
    // -----------------------------------------------------^^^^^^^^^^^^^^^^^^
    

    and so you get

    LoopCount: 4<br>LoopCount: 5
    

    and so on.

    If you put the innerHTML first on that line, you'll reverse the order:

    target.innerHTML = target.innerHTML + "<br>LoopCount: " + loopCount;