Closure is of the most beautiful and sometimes intricate part to understand in Javascipt. In simple words, a closure gives you access to an outer function’s scope from an inner function.

Closures allow us to invoke an inner function outside its enclosing function while maintaining access to the enclosing function’s lexical scope(i.e identifiers in its enclosing function).

See this example to better understand:

function outer(){ 
    let value =10;
    return function(){
        console.log(value);
    }
}
const innerFunction = outer();
innerFunction();// 10

We define an outer function and return a function from it. Here the returned function is a higher order function.

We call the outer function and store it in innerFunction variable. innerFunction retains the value even after the outer function has returned. That’s closures in action.

Functions are first class citizens in javascript. Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.

Let’s see closures in action with examples.


1. How many times a function is called?

function outer() {
	  let counter = 0;
	  return function incrementCounter () {
	    counter++;
	    console.log(`Called ${counter} times`);
	  }
	}

	const increment = outer();
	increment(); // Called 1 times
	increment(); // Called 2 times
	increment(); // Called 3 times

Examine the code for the outer function. Notice that we are returning a function and that function is using counter variable that’s outside of its scope. Closure is how we access the variable from the outer scope.

#ui #javascript #closure #examples

Closures with examples
1.20 GEEK