Closures in Javascript learn the easy way

Written by officialrahulmandal | Published 2019/01/24
Tech Story Tags: javascript | nodejs | programming | web-development

TLDRvia the TL;DR App

What are closures?

A closure is an inner function that has access to the outer (enclosing) function’s variables — scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables

In simple words that is literally what it is, a function inside a function, that relies on variables in the outside function to work .

The best way of understanding a concept is by doing it .

so let’s have some examples on closures .

function doSomeMath(){var a=5;var b=4;var sum=a+b;

return sum;}

var theResult = doSomeMath();

console.log("The result:", theResult);

We do some math here, set up three variables, and add one variable to the other, and return the sum. Now let’s take a closer look at how exactly the browser would handle this code. When we run the script in the browser. It first discovers this function doSomeMath, but does nothing to it. Then it gets down here and finds the variable theResult, and sees that doSomeMath has been assigned to this variable.

That means it needs to run doSomeMath, so it jumps up to the function, sets up the three variables, performs the math, then places the result inside the sum variable, and returns the sum variable. The contents of the sum variable is then placed inside theResult, and the doSomeMath function is effectively closed down, and everything inside it is thrown away. The only thing we’re left with inside theResult is the value nine,so that means if I go to my console, and I try to call for A, or B, or sum, I get nothing.

That’s because they sit inside the scope of the function doSomeMath. We are now outside the scope, and these variables do not exist. So far, there’s nothing new here. Now let’s change this example a little bit.

function doSomeMath(){var a=5;var b=4;

function multiply(){var result = a*b;return result;}

return multiply;}

var theResult = doSomeMath();

console.log("The result:", theResult);

If I save this now, you’ll see over here in the console, that the variable theResult, now holds the total function multiply with all of its contents.

If I save this now, you’ll see over here in the console, that the variable theResult, now holds the total function multiply with all of its contents.

That’s weird, and based on what we already know about how functions work, this shouldn’t work. Why am I saying this? Well, think about this for a second. The browser reads from the top right? So it first finds the function doSomeMath, but does nothing to it. Then it jumps down to the variable Result, and sees that doSomeMath has been assigned to it, so it goes up to the top, and runs the entire function. It sets up the two variables, registers the multiply function, then goes down to the bottom and sees oh, I want to return to multiply function, but I don’t want to run it, I’m just going to return it as if it was a variable, so I’ll just place this multiply function inside theResult, and shut everything else down.

So technically, that means A and B should cease to exist, but if we look over in the console, it clearly doesn’t, it’s obviously still there. This here is what’s known as a closure. What’s happening is, this inside function multiply, relies on variables that have been defined in the outside function. And the browser is smart enough to understand oh, these things are related, so even though we’ve shut down the doSomeMath function, I’m going to keep these two variables alive, so that the multiply function can still use them.

So why do we have this feature?

Well, it has some interesting practical applications. Let me show you a very simple example. I’ll wipe out all my code, and then we’ll start fresh. If you’ve ever worked with Ems in CSS, you know they can be a bit of a pain to calculate,especially if you know what the pixel value you’re looking for is, and then you have to figure out what the similar Em value would be.

The trick with Ems is, if you know the pixel value of the current context, you can just take the pixel value you’re looking for, let’s say 32 pixels,and divide it by the current context pixel value, which, if you’re just working in the browser as a whole, is typically 16. The result of the desired pixel value, 32 divided by the root pixel value 16, gives you the Em value. Using a closure, we can create a function that helps generate these numbers for us.

First I’ll set up a new function, and I’ll call it giveMeEms. This function has an argument, (pixels). This is the pixel value we want to convert into Ems. Inside the function, we have a variable called baseValue. I’ll set that one to 16, because 16 is the base font size for most browsers. Then we set up an inside function called doTheMath. Inside doTheMath, we’ll simply return pixels/baseValue.

See here we’re grabbing that pixels argument, and using it inside the inside function, and then grabbing the variable base value, and also using it inside the inside function. And then finally to close things off, we return doTheMath. Now we can set up a series of variables calling for giveMeEms, and different pixel sizes, and get the values in return. So I’ll set up var smallSize = giveMeEms.

And here I’ll pass (12), so I’m looking for that Em value that would be equivalent to 12 pixels. Then var mediumSize = giveMeEms(18), var largeSize = giveMeEms(24). And finally var xlargeSize = giveMeEms(32).

Then to actually get the results here, I will console.log(“Small size: “ and smallSize). I’ll just copy these. Medium, large, extra large And finally, I need to run the small size, medium size, large size, and extra large size variables as functions.

function giveMeEms(pixels){var baseValue = 16;

function doTheMath(){return pixels/baseValue;}

return doTheMath;}

var smallSize = giveMeEms(12);var mediumSize = giveMeEms(18);var largeSize = giveMeEms(24);var xlargeSize = giveMeEms(32);

console.log("Small Size", smallSize())console.log("Medium Size", mediumSize())console.log("Large Size", largeSize())console.log("Extra Large Size", xlargeSize())

And when I save this, and run it in the browser,

I get the Em sizes for each of these sizes, 0.75, 1.125, 1.5, and 2. Again, this is only possible because of closures. In this case, the closure here contains both this variable base value, and the value of pixels, even though technically, the giveMeEms function has already run, and when we’re calling it down here, we shouldn’t be able to get these values.

Closures in JavaScript are a fascinating topic, and this particular rabbit hole goes way deeper than what I’ve shown you here. To get a better understanding of just how powerful closures are, where you can use them to your advantage, and when they might cause problems, you should check out the MDN article on closures. It gives you lots of examples, lots of further details about exactly what’s going on, and shows you how you can use them in your everyday code.

Hi, My name is Rahul Kumar Mandal. I am a Full Stack Developer .I write about JavaScript, NodeJS and reactjs. And sharing my worldview with everyone join my quest by following me at Twitter or Medium.

I hope you enjoyed this article on Closures in JavaScript.

Feel free to comment and like this article so that others can find it easily on Medium!

And thank you for reading this article if you like it then share it, with your friends and enemies. And I will be writing more about JavaScript, NodeJS,react.js stay connected with me.


Published by HackerNoon on 2019/01/24