DEV Community

Ravina Deogadkar
Ravina Deogadkar

Posted on

Javascript: Closures

Another important and mostly used topic under Javascript is Closure; we might have come acrossed them several times.

Closure is a term refers to function enclosed within another function having access to the outer function scope. Closure is a combination of function and it's lexical within which the function is defined. Environment consists of variables declared containing data on which function operates. Closure is created everytime a function is defined.

function init(){
let name = "Ravina";
function displayName(){
alert(name);
}
displayName();
}

Here function init(), defines a variable name which is assigned a value Ravina and a enclosed function displayName() uses outer function scoped variable name. displayName function is called within the outer function. Since the scope is limited to it's outer function only.

But what is we need the inner function to be available outside the scope of outer function?

We can do so by returning the inner function. Let's have a look at below code.

function init(){
let name = "Ravina";
function displayName(){
alert(name);
}
return displayName;
}

let myfunc=init();
myfunc();

So here we have init() function with return displayName statement causing function to be returned before execution. The myfunc variable is assigned displayName function and it executed absolutely fine. But scope of variable ends after function completes execution. While this is not a case with Javascript, function forms closure. In this case myfunc variable holds reference to displayName function that is created when init function is run. The instance of displayName function holds reference of lexical environment in which it is defined. Hence variable name remains available even within the myfunc function.

Closure scope chain

Every closure has three scopes

  • global scope
  • outer function scope
  • local scope

In some cases there could be multiple nested outer functions and each of the outer functions variables are overridden.

Uses

Since closure combines together the function and the data it operates on. Closures would be most useful in achieving the Object oriented programming mechanism where object encapsulates data and the functions.
Closures could be used anywhere in a project like an object.

Top comments (0)