for (var i = 0; i < 3; i++) {
(function(i) {
setTimeout(function() {
console.log(i); // Output: 0, 1, 2
}, 1000);
})(i);
}
Closures are a powerful tool in JavaScript that allow functions to retain access to variables from their lexical scope. They are essential for creating private variables, maintaining state in asynchronous code, and more. However, developers must be mindful of potential pitfalls like memory leaks and unexpected behavior in loops.