Why let and var bindings behave differently using setTimeout function?

Why let and var bindings behave differently using setTimeout function?
Why let and var bindings behave differently using setTimeout function?

In JavaScript, setTimeout is a function that runs a callback function after a specified amount of time has passed. However, the behavior of var and let bindings can be different when used in conjunction with setTimeout due to their different scoping rules.

When a variable is declared with var inside a function, it’s accessible throughout the entire function, regardless of whether it’s inside a block or not. This means that when a setTimeout callback function is invoked, it has access to the variables declared with var in the outer scope.

Here’s an example that shows how var behaves with setTimeout:

function varExample() {
  for (var i = 0; i < 3; i++) {
    setTimeout(function() {
      console.log(i);
    }, 0);
  }
}
varExample(); // Output: 3 3 3

In the above example, the output is 3 three times because by the time the callback function is invoked, the for-loop has already completed and the variable i has the final value of 3.

On the other hand, variables declared with let are block-scoped, which means that they’re only accessible within the block in which they were declared. let bindings can be captured by closures, so they can be used inside the callback function of setTimeout without any problem

function letExample() {
  for (let i = 0; i < 3; i++) {
    setTimeout(function() {
      console.log(i);
    }, 0);
  }
}
letExample(); // Output: 0 1 2

Leave a Reply