What is a loop trap
var a = []; for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); / / 10Copy the code
- Because the variable I used in an anonymous function is declared out of scope, it forms a closure
- I is in the global scope
- So the anonymous functions created in the loop all point to the same variable
A loop trap is one that appears to require a separate variable for every newly created function, but is not implemented, so it is called a loop trap
IIFE executes the function in real time
var a = []; for (var i = 0; i < 10; i++) { (function(n) { a[i] = function () { console.log(n); }; })(i) } a[6](); / / 10Copy the code
The solution to this problem is to create a new scope.
Since function scopes were only available before ES6, the only solution was to create new functions. So create a new scope by creating an instant function.
Let creates block-level scope resolution
var a = []; for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); / / 6Copy the code
The interview guide
ES5’s IIFE and ES6’s let achieve the same effect. Both create new scopes, but one uses the old syntax to create new functions, while the other uses the new syntax to create new functions.