DEV Community

Shivashish Yadav
Shivashish Yadav

Posted on • Originally published at shiva.hashnode.dev on

What is a closure in Javascript?

Introduction

In JavaScript, internal and external functions exist, and internal functions can access local variables of external functions. Also, even after the outer function is destroyed, the inner function can access the variables of the outer function. Closures take advantage of this property. Let's look at an example.

πŸ’‘Function Example

function outter() {
  let title = 'hello everyone';
  return function () {
    alert(title);
  };
}

inner = outter();
inner();

Enter fullscreen mode Exit fullscreen mode

The above code defines the outer function , returns the function to the inner function , and stores the execution result of the outer function in the inner variable.

πŸ” Example code execution result

hello everyone

Enter fullscreen mode Exit fullscreen mode

When you run the code, a warning window 'hello everyone' is displayed as shown in the picture above. 'coding everybody' is the value contained in the title, which is a local variable of the external function. The properties of the closure that can be seen in the example above are

inner = outter();

Enter fullscreen mode Exit fullscreen mode

In the above code, the outer function returns the inner function, even though the outer function is terminated.

inner();

Enter fullscreen mode Exit fullscreen mode

Afterward, when the inner function is called, the title variable existing in the outer function can be accessed.

In other words, the characteristic of closures is that not only can the external function containing the internal function be accessed but also the external function and local variables of the external function can be accessed through the internal function even after the external function is terminated.

Top comments (0)