Closures & Callback Functions
Closures are a powerful feature in JavaScript that enable state encapsulation. A closure is formed when a function remembers and accesses its lexical scope, even when executed outside that scope.
1 Closures and Encapsulating States
A closure occurs when a nested inner function is returned from an outer function, preserving reference definitions of variables in the outer function's scope. This allows you to emulate private variables by restricting direct access to states.
2 Callback functions
Callbacks are functions passed as arguments to other functions, which are executed after some event or calculation completes. Let's trace closures and callback logic:
JavaScript — Closures and Callbacks
▶ Run Code
// Closure structure encapsulating a count state
function createCounter() {
let count = 0; // Private state variable
return {
increment() {
count++;
return count;
},
getCount() {
return count;
}
};
}
const counter = createCounter();
console.log("Count: " + counter.increment());
console.log("Count: " + counter.increment());
// console.log(count); // 🚨 Throws ReferenceError: count is not defined!
// Callback execution
function processUser(name, callback) {
console.log("Processing user " + name);
callback();
}
processUser("Alice", () => {
console.log("Processing completed!");
});
3 Code Challenge
Challenge: Write a function called `createMultiplier(factor)` that returns a closure function. The returned function should accept a number and return it multiplied by the factor. Initialize a `double` multiplier and use it to double `5`.