DEV Community

Discussion on: JavaScript Closures: A Simple Explanation.

Collapse
 
stereobooster profile image
stereobooster

You can mention binding as well. let has lexical scope binding (e.g. it binded inside for ), where is var has scope of function body:

function countdown(upto) {
  for (let i = 0; i < upto; i++) {
    setTimeout(() => console.log(i), 1000);
  }
};
countdown(5); // Output: 0 1 2 3 4

Or using bind:

function arrayOfNums(num) {
  var output = [];
  for (var i = 0; i < num; i++) {
    output.push((function(x) { return x; }).bind(null, i)); 
  }
  return output;
}
arr[0](); // Output: 0