JS Closure — Example
Hello There,
Thanks for having patience, I apologize for the delay. As promised in my previous story, here I am back with the example of Closure in the JS.
According to the common book definitions, you can say that a closure is created when a function keeps a link to its parent scope even after the parent has returned. And, every function is a closure because, at the very least, every function maintains access to the global scope, which is never destroyed.
Before we go through the example, let’s recall the JS fundamentals. We do know that there is a global scope and every function has the local scope. That means following:
- Everything defined outside any function and the functions itself (as they defined in global scope) fall in the global scope.
- Everything defined inside a function becomes local and can be accessible within the scope of belonging functions.
Hence, every function maintains a secret link to the environment (the scope) in which it was created. But, most of the time this scope is destroyed unless something interesting happens (as we will discuss below) that causes this scope to be maintained
Now as discussed in the previous story we need to know, what happened inside a function(more like a coffee machine) when it was called. In fact, we have to maintain that function’s scope by injecting something interesting.
Get Premchand Kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
There are few defined ways in JS to achieve the same. Lets discuss th first one: 1. Could you please have a look at below example?
var a = “global variable”;
var F = function () {
var b = “local variable”;
var N = function () {
var c = “inner local”;
return b;
};
return N;
};
Here we have a function F, that contains the variable b , which is local, and therefore inaccessible from the global space:
> b;
ReferenceError: b is not defined
The function N has access to its private space, to the F() function’s space, and to the global space. So, it can see b. Since F() is callable from the global space (it’s a global function), you can call it and assign the returned value to another global variable.
The result: a new global function that has access to the F() function’s private space:
> var inner = F();
> inner();
“local variable”
This is not the only way to break the local scope and get accessible from outside, few more are there which would be continued in next stories.
Thanks for being patient for the same.
References :-
Object-Oriented JavaScript — Second Edition
by
Stoyan Stefanov
Kumar Chetan Sharma





