'Can someone explain simple var vs let behavior in certain js function? [duplicate]

Can someone explain to me this:

function f(){
    for(var i=0; i<4; i++){
        setTimeout(()=> {console.log(i)}, 0);
    }
    console.log('test');
}

When I call this function it returns: test 4 4 4 4, but when I write LET instead of VAR it returns test 0 1 2 3.

Now I am familiar with why test is printed first, and with the under the hood concepts. But I just dont know why it is this way...



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source