Exploring Closures
In JavaScript, closures are a powerful feature that allows functions to retain access to variables from their outer scope even after they have finished executing. This means that functions can still access and use variables that were defined outside of their own scope.
Closures are created when an inner function references variables from its outer function. The inner function has access to the outer function's scope, including its variables, parameters, and even other nested functions.
Closures are commonly used to create private variables and data encapsulation. They can also be used to create higher-order functions and implement callback functions.
Here's an example of a closure in action:
1// Example of a closure
2const outerFunction = () => {
3 const outerVariable = 'I am outside!';
4
5 const innerFunction = () => {
6 console.log(outerVariable);
7 };
8
9 return innerFunction;
10};
11
12const closure = outerFunction();
13closure(); // Output: 'I am outside'
In this example, the innerFunction
is created inside the outerFunction
and references the outerVariable
. Even after the outerFunction
has finished executing, the innerFunction
retains access to outerVariable
and can still log its value.
By understanding closures, you can leverage their power to write cleaner and more efficient code with enhanced data privacy and functionality.
xxxxxxxxxx
// Basketball player example
const playerName = 'Kobe Bryant';
function basketballStats() {
const pointsPerGame = 25;
const reboundsPerGame = 7;
function playerStats() {
console.log(`${playerName} averaged ${pointsPerGame} points per game and ${reboundsPerGame} rebounds per game.`);
}
playerStats();
}
basketballStats();