DEV Community

Mursal Furqan
Mursal Furqan

Posted on

Closures in JavaScript - The easy way

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()
Enter fullscreen mode Exit fullscreen mode

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.
Image description
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>
Enter fullscreen mode Exit fullscreen mode
body {
     font-size: 12px;
}
h1 {
     font-size: 1.5em;
}
Enter fullscreen mode Exit fullscreen mode

Image description

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
Enter fullscreen mode Exit fullscreen mode

πŸ“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 😜
Image description

Discussion (2)

Collapse
lukeshiru profile image
LUKESHIRU

Nice article! For folks wondering how this looks like with modern syntax, is pretty similar:

const makeSizer = size => () =>
    document.body.style.setProperty("font-size", `${size}px`);

const size12 = makeSizer(12);
const size14 = makeSizer(14);

document.querySelector("#size-12").addEventListener("click", size12);
document.querySelector("#size-14").addEventListener("click", size14);
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
alirazalalani profile image
Aliraza Lalani

Nicely explained :)