Calling All New Developers. Understand How do JS closures work?

Closures is a JavaScript topic that’s absolutely vital to understand

if you’re going to advance at all in understanding and writing the language.

However, it’s also very difficult to understand,

Take a good look at MDN definition of Closures:-

closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).

In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time

We’re going to write a bit of code that will show the power of closures.

And then we’ll understand what’s really going on under the hood.

// I'm gonna go ahead and create my good old ola function that returns another function

function ola(hi) {
 return function(name) {
   console.log(hi + name)
}}

// So how do we invokes the function that returns a function

ola('hello ')('afzal');  // Expected Output - hello afzal

// Did you noticed something unusual already happened.
// let's do this a bit differently.

var sayHello = ola('hello ');
sayHello('afzal') // Expected Output -  hello afzal

How does the sayHello function at line 16 still know the hi variable?

How is that even possible?

It’s possible because of closures. Closures are simply a feature of the JavaScript programming language.

It doesn’t matter when we invoke a function.

The JavaScript engine will always make sure that whatever function I’m currently running can access the variables declared in parent function.

Now consider the following example from MDN

function sum(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = sum(5);
var add10 = sum(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

In this example, they have defined a function sum(x), which takes a single argument, x, and returns a new function. The function it returns takes a single argument, y, and returns the sum of x and y.

add5 and add10 are both closures. They share the same function body definition, but store different lexical environments. In add5‘s lexical environment, x is 5, while in the lexical environment for add10x is 10.

Private methods with closures:-

Closure is useful in hiding implementation detail in JavaScript. In other words, it can be useful to create private variables or functions.

The following example shows how to create private functions & variable.

var ola = (function() {
var privateCounter = 0;
 function changeBy(val) {
  privateCounter += val;
  }
 return {
  increase: function() {
   changeBy(1);
    },
  decrease: function() {
   changeBy(-1);
    },
  value: function() {
   return privateCounter;
    }
  };   
})();

alert(ola.value()); // 0
ola.increase();
ola.increase();
alert(ola.value()); // 2
ola.decrease();
alert(ola.value()); // 1

In the above example, increase(), decrease() and value() becomes public function because they are included in the return object,

Whereas changeBy() function becomes private function because it is not returned and only used internally by increase() and decrease().

Closing Notes: It may be slightly difficult to get the concept of closure at once but try experimenting with closure in different scenarios like for creating getter/setter, callbacks and so on.

Thanks for reading, If you have any questions , please ask questions in the comments below.

I will personally answer all the questions, or alternatively, you can Dm me on Facebook too.

If this post was helpful, help me back by clicking the Share button.

More Articles:-

The Ultimate Guide to become a full stack web developer in 3 easy step

7 Amazing Array Methods to Boost your Javascript Skills Today

3 weird ways to create javascript objects (Learn my tricks Now)

Who Else Wants to Clear confusion about Javascript Hoisting [Step-by-Step]

Tanisk jha

Mission-Driven Self taught Software Developer with a passion for thoughtful UI Design, collaboration and writing.
Tanisk jha

2 thoughts on “Calling All New Developers. Understand How do JS closures work?

  1. Hey man, you have one typo, for example
    “`
    var sayHello = ola(‘hello’);
    sayHello(‘Tony’) // Expected Output – hello afzal
    “`

    Your site is really cool, but that one error could make another pal not understand what you are trying to convey.

    #respecto

Leave a Reply

Your email address will not be published. Required fields are marked *