For/off loop is displaying undefined .. when the button get clicked!

<body>
    <div class="btn">
        <button>Click Me</button>
    </div>
    <p id="demo"></p>

    <script>
        let mySelf = ['Bilal' , 'Shuja' , 23];
        let x,display ="";
        let btn  = document.querySelector('.btn');
        for(x of mySelf){
            display += mySelf[x] +" ";
    }
    btn.addEventListener('click',()=>{
                document.getElementById('demo').innerHTML = display;
        })
            
    </script>
    
</body>

Hi @billy.s56. The problem is with display += mySelf[x] +" "; . x is not an index of the array mySelf. Try display += x +" ";.

1 Like

It works !!! Thank you so much @nibble :slight_smile:

1 Like

You can read more about for…of here

1 Like