While practicing javascript I came across with one doubt I am printing variable i value using var and using let keyword and both the time getting different result but unable to understand why I need some explanation for this??
with var i
<script>
(function timer(){
for(let i=0;i<=5;i++){
setTimeout(
function clog(){
console.log(i)
},i*1000 );
}
}
)();
</script>
output ::
while using var
<script>
(function timer(){
for(var i=0;i<=5;i++){
setTimeout(
function clog(){
console.log(i)
},i*1000 );
}
}
)();
</script>
output :: 
>Solution :
It is because of globally (var) or block scoped (let) value processing of javascript.
In var, variable i is globally changing and the loop finishes before settimeout function runs, so the i becomming 6 globally and console log writes yo it as 6.
In let, for every loop iteration there is an i variable belongs only that scope and settimeout function takes it, so the even if the loop finish it’s job console log writes local varible i as 0,1,2,3,4,5.
I hope i tell myself correctly.
ref: Javascript MDN