JavaScript Closures Explained with Practical Examples for Beginners
Learn what JavaScript closures are and how to use them with simple examples perfect for beginners.
Closures are a fundamental concept in JavaScript that every beginner should understand. They allow functions to access variables from an outer function even after that outer function has finished executing. This opens up powerful ways to write flexible and concise code.
Let's start with a simple example to explain what a closure is.
function outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
const increment = outer();
increment(); // Output: 1
increment(); // Output: 2
increment(); // Output: 3In this example, `outer` declares a variable `count` and defines an inner function `inner` that increments and prints `count`. When we call `outer()`, it returns the `inner` function. The variable `increment` now holds this returned function.
Even though the `outer` function has finished running, the inner function still has access to the `count` variable. This happens because `inner` forms a closure—keeping the environment of `outer` alive. Each time you call `increment()`, you increase the same `count` value.
Closures are often used to create private variables or to implement function factories. Here's an example of a function factory using closures:
function makeMultiplier(multiplier) {
return function (number) {
return number * multiplier;
}
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5)); // Output: 10
console.log(triple(5)); // Output: 15Here, `makeMultiplier` returns a new function that multiplies its input by the given `multiplier`. Each returned function remembers the original `multiplier` value thanks to the closure.
To summarize, closures let functions remember the scope in which they were created. This is extremely useful for data privacy, creating function factories, and maintaining state in asynchronous code.
Keep practicing closures with different examples, and soon you'll feel comfortable using this powerful JavaScript feature!