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:-

A 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 functionfunction ola(hi) {
return function(name) {
  console.log(hi + name)
}}// So how do we invokes the function that returns a functionola('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 add10, x is 10.

Closure is also 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() {
 decrease: function() {
 value: function() {
  return privateCounter;
})();alert(ola.value()); // 0
alert(ola.value()); // 2
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, Happy Hacking