Middle
Tell about closures in JavaScript and give examples of their use.
sobes.tech AI
Answer from AI
Closure is a function together with its lexical environment (scope), "remembering" variables from the outer function even after its execution has finished.
Main idea: the inner function has access to the variables of the outer function where it was created.
Examples of usage:
-
State preservation:
function createCounter() { let count = 0; return function() { count++; console.log(count); }; } const counter1 = createCounter(); // Create the first counter const counter2 = createCounter(); // Create the second counter counter1(); // Outputs: 1 (first counter) counter1(); // Outputs: 2 (first counter) counter2(); // Outputs: 1 (second counter) -
Encapsulation (IIFE):
(function() { let privateVar = "Private variable"; // This code has access to privateVar function showPrivateVar() { console.log(privateVar); } showPrivateVar(); // Outputs: Private variable })(); // Access attempt from outside will cause an error // console.log(privateVar); // Error: privateVar is not defined -
Creating function factories:
function createGreeter(greeting) { return function(name) { console.log(`${greeting}, ${name}!`); }; } const sayHello = createGreeter("Hello"); const sayHi = createGreeter("Hi"); sayHello("World"); // Outputs: Hello, World! sayHi("Friend"); // Outputs: Hi, Friend! -
Working with asynchronous operations (old approach with
var):// Problem with 'var' without closure for (var i = 0; i < 3; i++) { setTimeout(function() { console.log(i); // Will output 3, 3, 3 }, 100); } // Solution with closure (using IIFE) for (var j = 0; j < 3; j++) { (function(index) { setTimeout(function() { console.log(index); // Will output 0, 1, 2 }, 100); })(j); } // Modern solution with `let` (less need for explicit closure in this case) for (let k = 0; k < 3; k++) { setTimeout(function() { console.log(k); // Will output 0, 1, 2 }, 100); }
Closures can consume more memory as they keep a reference to external variables, but their flexibility and capabilities for encapsulation and state preservation make them an important tool.