DEV Community

Cover image for Javascript Closures
Amol Shelke
Amol Shelke

Posted on

Javascript Closures

JavaScript variables can belong to the local or global scope.

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

Global variable

A function can access all variable defined inside the function like this:-

 function calculateNum() {
  let a = 4;
  return a * a 
}

Enter fullscreen mode Exit fullscreen mode

But a function can also access the variable outside of the function like this:-

let i = 4; 
function calculateNum() {
return i * i
}
Enter fullscreen mode Exit fullscreen mode

in the above example a is a global variable.
In a webpage global variable belong to the window object.

In the first example, a is a local variable.

A local variable can only used inside the function where it is defined. it is hidden from other function they can't use them.

Global and local variables with the same name are different variables. Modifying one, does not modify the other.

Closures Example

const add = (function () {
  let counter = 0;
  return function () {counter += 1; return counter}
})();

add();
add();
add();

Enter fullscreen mode Exit fullscreen mode

Example explained

  • a variable add is assigned to the returning value of a self invoking function

  • a self invoking function only runs a once. it's sets the counter set to(0) and return a function expression

  • This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.

  • This is called a JavaScript closure. It makes it possible for a function to have "private" variables.

  • The counter is protected by the scope of the anonymous function, and can only be changed using the add function.

A closure is a function having access to the parent scope, even after the parent function has closed

Top comments (0)