javascriptjquery

click callback looses context depending on var or let


If you try this code with "let i" it works, and with "var i" it doesn't work.

Can you explain me why?

$(document).ready(function () {
    for (let i=0; i<20; i++) {
        $('<button />').append(i).appendTo('body').click(function() {
            console.log(i);
        });
    }
});

Solution

  • var will declare it in the scope of the anonymous function passed to the ready method, meaning there can be only be one i in the anonymous function scope hence you are getting this issue, the last number that was updated for i is shown!. When you define with let its scope is limited to the block on which its defined, which is the for loop, hence it works fine.

    For further info visit here

    $(document).ready(function () {
        for (let i=0; i<20; i++) {
            $('<button />').append(i).appendTo('body').click(function() {
                console.log(i);
            });
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>