DEV Community

Cover image for Concept of closure in javascript
Kamalesh AR
Kamalesh AR

Posted on

Concept of closure in javascript

Closures:

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives a function access to its outer scope. In JavaScript, closures are created every time a function is created, at function creation time.

JavaScript variables can belong to:

  1. The local scope
  2. The global scope

Global variables can be made local (private) with closures.

Closures make it possible for a function to have "private" variables.

A closure is created when a function remembers the variables from its outer scope, even after the outer function has finished executing.

  • Retains access to outer function variables.
  • Preserves the lexical scope.
  • Allows data encapsulation and privacy.
  • Commonly used in callbacks and asynchronous code.

Lexical Scoping:

Closures rely on lexical scoping, which means a function’s scope is determined by where it is defined, not where it is executed.

  • A function retains access to the scope where it was defined.
  • Inner functions can access outer function variables.
  • Enables closures to “remember” their environment.

Private Variables

Closures allow a function to keep variables private and accessible only within that function, which is commonly used in modules to protect data from being accessed or modified by other parts of the program.

  • Helps achieve data encapsulation
  • Creates private variables
  • Prevents accidental data modification

Example 1:

function makeAdder(x){
    return function(y){
        return x+y
    }
}
let add5 = makeAdder(5)
console.log(add5(10))
Enter fullscreen mode Exit fullscreen mode

Output:

15
Enter fullscreen mode Exit fullscreen mode

Example 2:

function myCounter() {
  let counter = 0;//variable in outer function
 function inner() {
    counter++;//inner function uses other variable
    console.log(counter);
   }
return inner;
}
const add = myCounter();
add();//1
add();//2
add();//3
const adding = myCounter();
adding();//1
adding();//2
add();//4
Enter fullscreen mode Exit fullscreen mode

Eventhough, the outer function has finished, the inner function remembers the count. This is called closure.

References:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
https://www.w3schools.com/js/js_function_closures.asp
https://www.geeksforgeeks.org/javascript/closure-in-javascript/

Top comments (0)