Closures are one of the most important topics in JavaScript that you must understand to take better grasp over the javascript. The earlier you know about Closures, the better you will write your JavaScript code, so in this article, i am going to explain about it, and you should go through it whether you are beginner or expert, you will still learn something new.
What is Closure in Javascript?
Closure is not a tangible thing in JavaScript. By that I mean: it’s not like a variable holding a value, neither is it a function. And more importantly, neither is it an object.So, a closure is a name given to a feature in the language by which a nested function executed after the execution of the outer function can still access outer function’s scope.
Or you can say it in different words, a closure is an inner function that has access to the variables of the enclosing function – the scope chain.
A closure has three scope chains:
- Has access to its own scope, i.e. can access the variables stated in the function body.
- Has access to the variables created by the enclosing function.
- Has access to the variables created globally.
A closure has the following major properties:
- Most important, the inner function has access not only to its enclosing functions, but also to their parameters.
- The moment a closure is created, its entire environment is preserved as is. This means that the value of local variables is preserved as well. They don’t get “destroyed” anymore.
- A closure can help you access variables outside a function.
Therefore, you can create a closure by adding a function inside another function, keeping in mind the properties described above. To better understand how that happens, let’s see an example and some use cases.
For example:
function bake(x) {
return function(y) {
return `${x}: flavor ${y}`;
};
}
var pie = bake("pie");
var cupcake = bake("cupcake");
console.log(pie("strawberry")); // pie: flavor strawberry
console.log(cupcake("Mango")); // cupcake: flavor Mango
Now, take a look at the above code, when you called pie("strawberry")
it called the inner function of bake, but it also seamlessly remembered the variable x of it’s wrapping function.
Also, please note that the functions creating the closure are public, which means they can be accessed globally.
Definition from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures :A closure is the combination of a function and the lexical environment within which that function was declared.
Use of Closures in Javascript
Situations where you might want to do this are particularly common on the web. Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.
For instance, suppose we wish to add some buttons to a page that adjust the text size. One way of doing this is to specify the font-size of the body
element in pixels, then set the size of the other elements on the page (such as headers) using the relative em
unit:
body {
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
}
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.2em;
}
Our interactive text size buttons can change the font-size
property of the body
element, and the adjustments will be picked up by other elements on the page thanks to the relative units.
So,the JavaScript:
function makeSizer(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
var size12 = makeSizer(12); //change size to 12px
var size14 = makeSizer(14);//change size to 14px
var size16 = makeSizer(16);//change size to 16px
size12
, size14
, and size16
are now functions which will resize the body text to 12, 14, and 16 pixels, respectively. We can attach them to buttons (in this case links) as follows:
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
HTML
<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>
<a href="#" id="size-16">16</a>
Take a look at fiddle here, Source
Another Use is simple which is most widely used an example of javascript closure is while using jQuery.
$(document).ready(function(
var name = "qawithexperts";
// Closure having access to name variable
$('li').click(function(
alert(name);
));
));
Conclusions
You can use closures in Node.js to treat callbacks, in the asynchronous style. You can also rely on closures if you want to create something that can be manipulated outside a function without having to reinitialize it on each and every occasion. Closures are much like an abstraction mechanism that allows you to separate problems very clearly. The code is more compact, readable, organized and suitable for functional re-use.