DEV Community

Nashmeyah
Nashmeyah

Posted on

Closures

What is a closure?

"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 you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time." (MDN Web Docs, online)

In other words, a closures control what is and isn't in a scope for a function. A closure gives you access to an outer functions scope from within the function you are currently working in. The inner function will have access to the variables and objects from the outer functions scope.

Some examples of simple closures.

function increment() {

let i = 0;

  return function() {

    return i++;

  }

}

let addUp = increment();
//addUp() 0
//addUp() 1
//addUp() 2
Enter fullscreen mode Exit fullscreen mode

In this example, out inner function is pulling data from outside its scope and accessing a variable from the outer function.

Here is another example.

let num = 5;

const addTo = function(){
  let inner = 2;
  return num + inner;
}
console.log(addTo());
Enter fullscreen mode Exit fullscreen mode

In this example, 1 function is accessing a global variable from within the functions scope.

I hope you enjoyed this blog, have a wonderful day

Top comments (0)