DEV Community

Mofijul Haque
Mofijul Haque

Posted on • Edited on

Closure in JavaScript

In JavaScript, a closure is a mechanism or bundle of functions that has access to the variables in its parent scope, even after the parent function has completed executing. This allows the inner function to "remember" the values of the variables in its parent scope.

Here is an example of a closure:
`
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
}
}

let add5 = outerFunction(5);
console.log(add5(3)); // 8
`

In this example, the 'outerFunction' is defined and takes a single argument 'x'. It then returns a function 'innerFunction' that takes a single argument 'y'. The 'innerFunction' has access to the 'x' variable from its parent scope, even though the 'outerFunction ' has already completed executing.

When the 'add5' variable is defined, it is set to the returned value of calling 'outerFunction' with an argument of '5'. This means that 'add5' is now a reference to the 'innerFunction', with 'x' set to '5'. When 'add5' is invoked with an argument of '3', it returns '8', which is the sum of 5 and 3.

Closures are used extensively in JavaScript for a variety of purposes, such as:

**1. Creating private variables and methods

  1. Creating object data privacy
  2. Event handling
  3. Currying
  4. Creating stateful function**

Closures are one of the core concepts in JavaScript, and a good understanding of them is crucial for developing complex and maintainable JavaScript applications.

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

A closure is not a function

Collapse
 
mofijulhaque profile image
Mofijul Haque

Thank you for pointing the error I missed to put some words here😁