Functional programming is a programming paradigm that emphasizes functions as the primary building blocks of code. It focuses on immutability (avoiding modification of existing data) and pure functions (functions that always return the same output for the same input). Closures are a powerful concept in functional programming that leverage the way functions interact with their surrounding scope.
In JavaScript, a closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). This means that an inner function can access variables defined in its outer function’s scope, even after the outer function has finished executing.
JavaScript uses lexical scoping, which determines the visibility of variables based on their location in the code. Variables defined within a function are only accessible within that function’s scope. However, with closures, inner functions can access variables from their outer function’s scope, even if the outer function has already completed execution.
function createGreeter(greeting) {
// Outer function scope
return function() {
console.log(greeting + '!'); // Inner function accessing outer variable
};
}
const greetMorning = createGreeter('Good Morning');
const greetEvening = createGreeter('Good Evening');
greetMorning(); // Outputs: "Good Morning!"
greetEvening(); // Outputs: "Good Evening!"
createGreeter
takes a greeting
argument and defines an inner function.greeting
variable from the outer function’s scope (because of closure).createGreeter('Good Morning')
, it returns the inner function, which “remembers” the value of greeting
as “Good Morning”.createGreeter('Good Evening')
creates a separate closure with its own remembered value of greeting
.Benefits of Closures:
Advanced Use Cases:
function createCounter() {
let count = 0; // Private variable (not accessible outside)
return {
increment() {
count++;
},
getCount() {
return count;
}
};
}
const counter1 = createCounter();
counter1.increment();
counter1.increment();
console.log(counter1.getCount()); // Outputs: 2
const counter2 = createCounter(); // Separate closure with its own count
console.log(counter2.getCount()); // Outputs: 0
createCounter
function defines a private variable count
using let
.increment
and getCount
.count
variable because of the closure.createCounter
multiple times creates separate closures, each with its own private count
variable.Closures are a fundamental concept in functional programming and provide a powerful mechanism for creating functions with encapsulated state. Understanding closures allows you to write more modular, reusable, and expressive JavaScript code. By effectively using closures, you Happy coding !❤️