Search code examples
foreachequalsinnerhtmloperator-keyword

How can i loop through an array using innerHTML


    <div id="demo"></div><br>
    <script>
        let a = [1,2,3];
        a.forEach(function(item){
        document.getElementById('demo').innerHTML=item;
        })
    </script>

From the above code I can only get last digit. Why it is not showing all digits in the array. But When i use innerHTML+=item it is working fine. What is the difference between = and += here. I found that every tutorial explaining that += means x = x + y. But I believe there is a huge logic behind the scenes of += But no any one is expaining about this. It will be very helpfull anyone can explain this. Thanks in advance!


Solution

  • = and += are not the same

    document.getElementById('demo').innerHTML=item;
    

    will set to a single item each time in the loop. So going through three times your would be setting the innerHTML like this:

    • innerHTML = '1'

    • innerHTML = '2'

    • innerHTML = '3'

      document.getElementById('demo').innerHTML+=item;

    will append the item and is the same as

    document.getElementById('demo').innerHTML=document.getElementById('demo').innerHTML + item;
    

    So each time through you will be executing:

    • innerHTML = originalHTML + '1'
    • innerHTML = originalHTML + '1' + '2'
    • innerHTML = originalHTML + '1' + '2' + '3'