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.
A closure is a function that retains access to variables of the context it was created in even after said function call has returned.
function init() {
var name = "Mozilla" // name is a local variable created by init
function displayName() {
// displayName() is the inner function, a closure
alert(name) // use variable declared in the parent function
}
displayName()
}
init()
init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().
This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.
var awFunc = function(first) {
var someFunc = function(second) {
return first + second
}
return someFunc // note that I did not invoke this function i.e. I did not use someFunc(), but I did returned the function itself
}
var someMoreFunc = awFunc("awe") // At this point awFunc has finished running
console.log(someMoreFunc()) // This will return 'aweundefined'
console.log(someMoreFunc("some")) // returns awesome
Using Closures (Examples)
Among other things, closures are commonly used to give objects data privacy. Data privacy is an essential property that helps us program to an interface, not an implementation. This is an important concept that helps us build more robust software because implementation details are more likely to change in breaking ways than interface contracts.
To use a closure, simply define a function inside another function and expose it. To expose a function, return it or pass it to another function.
In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can’t get at the data from an outside scope except through the object’s privileged methods. In JavaScript, any exposed method defined within the closure scope is privileged. For example:
const getSecret = secret => {
return {
getPrivileged: () => secret,
}
}
In the example above, the getPrivileged() method is defined inside the scope of getSecret(), which gives it access to any variables from getSecret(), and makes it a privileged method. In this case, the parameter, secret.
Another example of closure
const outerFunc = () => {
let name = "Rohan"
const closureFunc = () => {
console.log(name)
}
return closureFunc()
}
var name = "Paul"
outerFunc() // => Will Print 'Rohan'
So whats going on above
First, when a function runs, a new function Lexical Environment is created automatically. That’s a general rule for all functions. That Lexical Environment is used to store local variables and parameters of the call.
During the function call we have two Lexical Environments: the inner one (for the function call) and the outer one (global):
The inner Lexical Environment corresponds to the current execution of that function.
When code wants to access a variable – it is first searched for in the inner Lexical Environment, then in the outer one, then the more outer one and so on until the end of the chain.
If a variable is not found anywhere, that’s an error in strict mode. Without use strict, an assignment to an undefined variable creates a new global variable, for backwards compatibility.
Some overall key points
Closure
- A closure is a function that remembers its outer variables and can access them.
- Combination of a function and the lexical environment within which that function was declared
- The
closureis the function object itself. - Accessing variables outside of the immediate lexical scope creates a closure.
- Happens when we have a nested functions.
- JavaScript engines also may optimize, discard variables that are unused to save memory.
- A
Lexical Environmentobject lives in theheapas long as there is a function which may use it. And when there are none, it is cleared. - All functions in JavaScript are closures.
- The internal property
[[Environment]]of a function, refers to the outer lexical environment
Lets look at this function
function outer() {
var b = 10
function inner() {
var a = 20
console.log(a + b)
}
return inner
}
/*
Here we have two functions:
an outer function outer which has a variable b, and returns the inner function
an inner function inner which has its variable called a, and accesses an outer variable b, within its function body
The scope of variable b is limited to the outer function, and the scope of variable a is limited to the inner function.
Let us now invoke the outer() function, and store the result of the outer() function in a variable X
*/
var X = outer()
Since the variables X is functions, we can execute them. In JavaScript, a function can be executed by adding () after the function name, such as X().
When we execute X(), we are essentially executing the inner function.
If I run < console.log(X()) > the output will be below
30 undefined
So the closure function inner() is getting the value of b = 10 from its enclosing outer() function ever after outer() function has returned.
Let’s see step-by-step what happens when the outer() function is first invoked:
-
- Variable b is created, its scope is limited to the outer() function, and its value is set to 10.
-
- The next line is a function declaration, so nothing to execute.
-
- On the last line, return inner looks for a variable called inner, finds that this variable inner is actually a function, and so returns the entire body of the function inner.
-
- Note that the return statement does not execute the inner function — a function is executed only when followed by () — , but rather the return statement returns the entire body of the function.
-
- The contents returned by the return statement are stored in X.
Thus, X will store the following:
function inner() { var a=20; console.log(a+b); }
This can be easily verified by adding the following to the JavaScript code:
console.log(typeof X) //X is of type function
-
- Function outer() finishes execution, and all variables within the scope of outer() now no longer exist.
-
- This last part is important to understand. Once a function completes its execution, any variables that were defined inside the function scope cease to exist.
The lifespan of a variable defined inside of a function is the lifespan of the function execution.
What this means is that in console.log(a+b), the variable b exists only during the execution of the the outer() function. Once the outer function has finished execution, the variable b no longer exists.
This is the most important point to realize. The variables inside the functions only come into existence when the function is running, and cease to exist once the functions completes execution.
Now see the main point of this exercise – that how a closure function retains its enclosing function’s variable values, even after the enclosing function has returned.
-
A. When we execute X(), we are essentially executing the
innerfunction. -
B. If I run < console.log(X()) > the output will be below
30
undefined
- C. So the closure function inner() is getting the value of b = 10 from its enclosing outer() function ever after outer() function has returned.
Let us examine step-by-step what happens when X() is executed the first time:
-
- Variable a is created, and its value is set to 20.
-
- JavaScript now tries to execute a + b. Here is where things get interesting. JavaScript knows that a exists since it just created it. However, variable b no longer exists. Since b is part of the outer function, b would only exist while the outer() function is in execution. Since the outer() function finished execution long before we invoked X(), any variables within the scope of the outer function cease to exist, and hence variable b no longer exists.
Closures
-
A. The inner function can access the variables of the enclosing function due to closures in JavaScript. In other words, the inner function preserves the scope chain of the enclosing function at the time the enclosing function was executed, and thus can access the enclosing function’s variables.
-
B. In our example, the inner function had preserved the value of b=10 when the outer() function was executed, and continued to preserve (closure) it.
-
C. It now refers to its scope chain and notices that it does have the value of variable b within its scope chain, since it had enclosed the value of b within a closure at the point when the outer function had executed.
-
D. Thus, JavaScript knows a=20 and b=10, and can calculate a+b.
So the inner function has three scope chains:
access to its own scope — variable a access to the outer function’s variables — variable b, which it enclosed access to any global variables that may be defined.
When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the function in the parameter. In other words, we aren’t passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function.
And since the containing function has the callback function in its parameter as a function definition, it can execute the callback anytime.
Note that the callback function is not executed immediately. It is “called back” (hence the name) at some specified point inside the containing function’s body.
Callback Functions Are Closures
When we pass a callback function as an argument to another function, the callback is executed at some point inside the containing function’s body just as if the callback were defined in the containing function. This means the callback is a closure. As we know, closures have access to the containing function’s scope, so the callback function can access the containing functions’ variables, and even the variables from the global scope.
Basic Principles when Implementing Callback Functions
1> Use Named OR Anonymous Functions as Callbacks – Here’s an example of named callback function
In most use case of Node/Express ecosystem, we use anonymous functions that were defined in the parameter of the containing function. That is one of the common patterns for using callback functions. Another popular pattern is to declare a named function and pass the name of that function to the parameter. Consider this:
// global variable
var allUserData = [];
// generic logStuff function that prints to console - this will be used as a callback function
function logStuff(userData) {
if (typeof userData === "string") {
console.log(userData);
} else if (typeof userData === "object") {
for (var item in userData) {
console.log(item + ": " + userData[item]);
}
}
}
// A function that takes two parameters, the last one a callback function
function getInput(options, callback) {
allUserData.push(options);
callback(options);
}
// When we call the getInput function, we pass logStuff as a parameter.
// So logStuff will be the function that will called back (or executed) inside the getInput function
getInput({ name: "Rich", speciality: "JavaScript" }, logStuff);
// name: Rich
// speciality: JavaScript
Make Sure Callback is a Function Before Executing It
It is always wise to check that the callback function passed in the parameter is indeed a function before calling it. Also, it is good practice to make the callback function optional.
Let’s refactor the getInput function from the previous example to ensure these checks are in place.
function getInput(options, callback) {
allUserData.push(options);
// Make sure the callback is a function
if (typeof callback === "function") {
// Call it, since we have confirmed it is callable
callback(options);
}
}
Without the check in place, if the getInput function is called either without the callback function as a parameter or in place of a function a non-function is passed, our code will result in a runtime error.
Note the following ways we frequently use callback functions in JavaScript, especially in modern web application development, in libraries, and in frameworks:
For asynchronous execution (such as reading files, and making HTTP requests) In Event Listeners/Handlers In setTimeout and setInterval methods For Generalization: code conciseness.
Lex-time
The first traditional phase of a standard language compiler is called lexing (aka, tokenizing). The lexing process examines a string of source code characters and assigns semantic meaning to the tokens as a result of some stateful parsing.
It is this concept which provides the foundation to understand what lexical scope is and where the name comes from.
To define it somewhat circularly, lexical scope is scope that is defined at lexing time. In other words, lexical scope is based on where variables and blocks of scope are authored, by me, at write time, and thus is (mostly) set in stone by the time the lexer processes my code.
It is considered best practice to treat lexical scope as, in fact, lexical-only, and thus entirely author-time in nature.
Let’s consider this block of code:
foo = a => {
let b = a * 2
bar = c => {
console.log(a, b, c)
}
bar(b * 3)
}
foo(2) // => 2 4 12
There are three nested scopes inherent in this code example. It may be helpful to think about these scopes as bubbles inside of each other.
Bubble 1 encompasses the global scope, and has just one identifier in it: foo.
Bubble 2 encompasses the scope of foo, which includes the three identifiers: a, bar and b.
Bubble 3 encompasses the scope of bar, and it includes just one identifier: c.
Scope bubbles are defined by where the blocks of scope are written, which one is nested inside the other, etc. For our understanding just assume, that each function creates a new bubble of scope.
The bubble for bar is entirely contained within the bubble for foo, because (and only because) that’s where we chose to define the function bar.
Notice that these nested bubbles are strictly nested. We’re not talking about Venn diagrams where the bubbles can cross boundaries. In other words, no bubble for some function can simultaneously exist (partially) inside two other outer scope bubbles, just as no function can partially be inside each of two parent functions.
Look-ups
The structure and relative placement of these scope bubbles fully explains to the Engine all the places it needs to look to find an identifier.
In the above code snippet, the Engine executes the console.log(..) statement and goes looking for the three referenced variables a, b, and c. It first starts with the innermost scope bubble, the scope of the bar(..) function. It won’t find a there, so it goes up one level, out to the next nearest scope bubble, the scope of foo(..). It finds a there, and so it uses that a. Same thing for b. But c, it does find inside of bar(..).
Had there been a c both inside of bar(..) and inside of foo(..), the console.log(..) statement would have found and used the one in bar(..), never getting to the one in foo(..).
Scope look-up stops once it finds the first match. The same identifier name can be specified at multiple layers of nested scope, which is called “shadowing” (the inner identifier “shadows” the outer identifier). Regardless of shadowing, scope look-up always starts at the innermost scope being executed at the time, and works its way outward/upward until the first match, and stops.
Note: Global variables are also automatically properties of the global object (window in browsers, global in node env), so it is possible to reference a global variable not directly by its lexical name, but instead indirectly as a property reference of the global object.
window.a
This technique gives access to a global variable which would otherwise be inaccessible due to it being shadowed. However, non-global shadowed variables cannot be accessed.
No matter where a function is invoked from, or even how it is invoked, its lexical scope is only defined by where the function was declared.
The lexical scope look-up process only applies to first-class identifiers, such as the a, b, and c. If you had a reference to foo.bar.baz in a piece of code, the lexical scope look-up would apply to finding the foo identifier, but once it locates that variable, object property-access rules take over to resolve the bar and baz properties, respectively.