Last active
April 5, 2024 16:55
-
-
Save adong/8d0c965e4233cfc0d30f52abb214cf5f to your computer and use it in GitHub Desktop.
javascript closure trap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// What is the result of the following? | |
for (var i=0; i<10; ++i) { | |
setTimeout(function() { | |
console.log(i); | |
}, 1000); | |
} | |
// using IIFE (immediately invoked function) | |
// with delay | |
for (var i=0; i<10; ++i) { | |
(function(j) { | |
setTimeout(function() { | |
console.log(j); | |
}, 1000); | |
})(i); | |
} | |
// without delay | |
for (var i=0; i<10; ++i) { | |
setTimeout((function(i) { | |
console.log(i); | |
})(i), 1000) | |
} | |
// wrap in a function | |
for (var i = 0; i < 10; i++) { | |
function timer(j) { | |
setTimeout(function() { | |
console.log(j); | |
}, j); | |
}; | |
timer(i); | |
} | |
// ES6, use let instead of var | |
for (let i=0; i<10; ++i) { | |
setTimeout(function() { | |
console.log(i); | |
}, 1000); | |
} | |
// Ref: https://hackernoon.com/how-to-use-javascript-closures-with-confidence-85cd1f841a6b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment