Why this code output comes 666666

(function timer() {
for (var i = 0; i <= 5; i++) {
setTimeout(()=> {
console.log(i);
}, i * 1000);
}
})();

Hi @aditya010sh_cda2cad8fd454417,
With the use of var you have a function scope, and only one shared binding for all of your loop iterations - i.e. the i in every setTimeout callback means the same variable that at the end is equal to 6 after loop iterations end.

Whereas with let you have a block scope and when used in the for loop you get a new binding for each iteration, the i in every setTimeout callback means a different variable, each of which has a different value: the first one will be 0, followed by 1 etc.

So this:

(function timer() {
  for (let i = 0; i <= 5; i++) {
    setTimeout(function clog() { console.log(i); }, i * 1000);
  }
})();

Prints 6 number of 6’s as the output.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.