Closures in JavaScript - The easy way
Mursal Furqan Kumbhar
Posted on December 5, 2021
Intro
Closure is a function inside another function that has access to outer function variables
Example ๐
function foo() {
let cat= '๐'
function bar() {
console.log(cat, ' is a cat!')
}
bar()
}
foo()
Explanation
In the above code, foo() created a local variable called cat and a function named bar(). The bar() function is an inner function that is defined inside foo().
Note that bar() don't have it's own variables. However, since inner function have access to variables of outer functions, bar() can access the variable cat.
Reason
Why do we learn itโ
Answer โก๏ธ These are used when one wants to extend the behavior such as pass variables, methods, etc. from an outer function to the inner function.๐
JavaScript is not a pure Object-Oriented Programming language, but you can achieve most of the OOP based behavior through closures.
Usage
Practical use case of closure is when you want to define a behavior and you want to attach some functions to manipulate those behavior with events.
I think this is the most obvious way of using closures and you should definitely use it to make your code shorter and development faster.
Let's see one of the best use case with code ๐
Example
Suppose we want to add a button to a page to adjust the text size. One way to do this is to attach font-size in pixels (px) inside body element and then set the size of other elements on page using relative em units.
<body>
...
<h1>Heading</h1>
<p>Some Text</p>
...
</body>
body {
font-size: 12px;
}
h1 {
font-size: 1.5em;
}
Now, closure function is given below โฌ
function makeSizer(size) {
return function() {
document.body.style.fontsize = size + 'px'
}
}
var size12 = makeSizer(12)
var size14 = makeSizer(14)
document.getElementById('size-12').onClick = size12
document.getElementById('size-14').onClick = size14
๐IKR, there are much better use cases of closures out there, but this was just to make the concept clear for young developers.
Why don't you all share your own use cases in the comments so that others may see live use cases of closures, in-action ๐
Posted on December 5, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.