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 π
Top comments (1)
Nicely explained :)