All You Need To Know About Javascript Closures
Have you ever wondered how different pieces of wood bundled together as a log of wood can make a beautiful table when put to use? Closure is the table created with different pieces of functions bundled together in a lexical environment.
if you are familiar with the way functions work in JavaScript, closure should be an addition to your application knowledge.
The example below will preempt the logic I want you to understand about closure:
function outerScope() {
let outerVariable = 'This is an outer variable';
function innerScope() {
console.log(outerVariable);
}
return innerScope;
}
const finalScope = outerScope();
finalScope();
Closure is a very logical topic, and it takes patience to understand. Therefore, I will encourage you to read through my explanation with patience and then apply it in the most understandable form to you.
outerScope
was declared in the example above, and it defines the innerScope
function. In the above definition, the innerScope function has access to outerVariable
defined under the outerScope
. This is the reason why you see console.log in the innerscope function where the outerVariable was called to ouput its function in the console.
We can see from the first two functions written above that other locally declared functions under the global function(outercope) can access any variable in the global scope. Each of these scopes is separated with the use of curly brackets {}.
The return exppression distingusihed from the functions declared is used to call the innerScope. Meanwhile, the innerscope has taken up the value from the variable outervariable and then the value being returned would be "This is an outervariable"
Although, the innerscope function had already completed its expression cycle after it returned the value passed from the outervariable to it. finalScope variable then holds a reference to the value being passed around from the initial global function declaration to the local function. The return of the value is then passed to finalscope and when it is being called, it returns the value "this is an outer variable"
This is just the basic function a closure can perform in Javascript. More explanation will be given on closure for you to understand the use and benefit of closure as you progress in your JavaScript learning.
Happy coding!
Subscribe to my newsletter
Read articles from Awopegba Damilola Mary directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Awopegba Damilola Mary
Awopegba Damilola Mary
A frontend developer