Practical Usage of Closure in JavaScript

Practical Usage of Closure in JavaScript

Closure is a very important concept that every JavaScript developer should understand. In my earlier post, I discussed what is closure and then, some examples to understand this concept. I highly recommend you go through that post and video before going into the details of this post.


Note – I am sharing all my JavaScript Developer Certification study notes here. Please provide your feedback if you see anything wrong or missing. Appreciate.

This post will cover some of the practical use of closures:

Private variables and methods

Private variables and methods can be implemented using closures.

var doOperation = function (value) {
//Private Variable
var initialValue = value;

//Private Function
var printValue = function () {
console.log(“Inside printValue: “ + initialValue);
};

return {
getValue: function () {
printValue();
},
incValue: function (value) {
initialValue += value;
console.log(initialValue);
},
decValue: function (value) {
initialValue -= value;
console.log(initialValue);
},
};
};

var Val = doOperation(100);

Val.incValue(50);
Val.decValue(25);
Val.incValue(500);
Val.getValue();

In the above example, the doOperation is returning an object with three methods getValue(), incValue() and decValue(). All of these three methods are basically accessing the private variable initialValue and private function printValue. Code outside its scope cannot directly access this variable, if we try to do that we will get an undefined value. This is the way we can use closure to implement the object-oriented concepts.

Function factories

We can use closure to create function factories i.e. use the outer function as a factory for creating functions with similar functionalities. Below is one example –
function greeting(greetingMsg) {
return function (toWhome) {
console.log(greetingMsg + “, “ + toWhome);
};
}

var morning = greeting(“Good Morning”);
var evening = greeting(“Good Evening”);
var night = greeting(“Good Night”);

morning(“James Bond”);
evening(“Shane Warne”);
night(“Brain Lara”);
As you can see I am returning a function that is printing a string containing the parameters from the outer function as well as inner function. This way we can keep our JavaScript DRY. 
These two are very common usage of closure. Please let me know in comments if you have any other examples.

Understand JavaScript Closure

 

Closure is a very important concept that every JavaScript developer should understand. In the post, I will provide a quick introduction of closure and then, I will be focusing on examples so that it will be easier for you to understand this concept. I will be sharing the video as well at the end of this post.

Note – I am sharing all my JavaScript Developer Certification study notes here. Please provide your feedback if you see anything wrong or missing. Appreciate.

What is a Closure?

As per MDN, “A closure is the combination of a function bundled together(enclosed) with references to its surrounding state. In other words, a closure gives you access to an outer function’s scope from an inner function”.

With the above example, let’s go through some examples to understand closure in details

Example 1

function sayHello() {
var message = “Hello World”;
function sayItNow() {
console.log(message);
}
return sayItNow;
}

var returnFunc = sayHello();
returnFunc();
Output:
Hello World
Explanation:
In the above example, the outer function sayHello creates a variable message, which is then being used inside the inner function sayItNow. Within the inner function, there is no variable declared, but due to closure, it can access the variable declared within the outer function.

Example 2

function increment() {
var number = 10;
function printTheNumber() {
console.log(number);
}
number++;
return printTheNumber;
}

var returnFunc = increment();
returnFunc();

Output:
11
Explanation:
In the above example, the outer function increment creates a variable number, which is then being used inside the inner function printTheNumber. Within the inner function, there is no variable declared, but due to closure, it can access the variable declared within the outer function. 
Now when I am storing the inner function which is coming as the return value from the outer function in the variable returnFunc and finally using that to call the inner function. This time I am getting the value printer as 11 instead of 10 because the variable number is still valid even though the declaration of the inner function is completed.

Video

Conclusion

With the above two examples, one thing is clear that closure will allow us to access variables defined in the enclosed parent function(s) even when the enclosing functions finish execution. Every function has its own execution context, which comprises of an environment that gives life to any variable declared within that function and a reference to its parent’s environment. A reference to the parent’s environment makes all variables in the parent’s scope available to all inner functions, regarding whether the inner functions are invoked outside or inside the scope in which they were created.
I hope this post will give you a clear picture of how closure works in JavaScript. Please provide your feedback in the comment section below.

Further Reading

Kitchener Canada Developer Group Event: All about events by Stephan Chandler-Garcia

 

Special thanks to our speaker, Stephan Chandler-Garcia, for the session on “All about events“. We discussed about Lightning Message Service, CustomEvent, the EMP API, Platform Events, Change Data Capture, WebSocket, and Consent Events!

You can register for all the upcoming sessions from the Kitchener Developer Group here.

You can get details (presentation and recording) of all the earlier sessions from the Kitchener Developer Group here.


Presentation


Recording


Functions in JavaScript

 

A JavaScript function is a block of organized, reusable code that is defined to perform a single, relation action. A function is executed when someone calls the function with the name.

Note – I am sharing all my JavaScript Developer Certification study notes here. Please provide your feedback if you see anything wrong or missing. Appreciate your help.

In JavaScript, functions are treated as first-class because they are treated as values. The example of treating function as values are – 

  • We can assign a function to a variable
  • We can store functions in an array
  • A function can be passed to another function as an argument
  • A function can be assigned to a property of an object.
You can find the video where I have explained everything here. I have also included the video at the end of this post.

Defining a function

A function is defined with the keyword function followed by the name of the function and then the optional functional parameters. Defining a function will not do anything unless you invoke the function. Below code shows a basic example of defining a function and then invoking the same function.
//Defining the function
function sayHello(name) {
console.log(“Hello, “ + name + ” to the world of JavaScript”);
}

//invoking the function
sayHello(“Shane James”);

Function returning value

By default, all functions return value, but in the above example, the return value is undefined. We can define the return and then store the return value in some variable like I have shown in the below example –
function sayHello(name) {
return “Hello, “ + name + ” to the world of JavaScript”;
}

let returnMessage = sayHello(“Shane James”);
console.log(returnMessage);

Difference between Argument and Parameters

An argument is a value that is being passed to the function while invoking the function.
A parameter is a variable that is listed as part of the function definition.
function sayHello(name) { //name is the function parameter
return “Hello, “ + name + ” to the world of JavaScript”;
}

let returnMessage = sayHello(“Shane James”); //”Shane James” is the function argument
console.log(returnMessage);

Why functions are treated as first-class in JavaScript?

As I mentioned before, functions in JavaScript are treated as first-class. We will see some examples below 

Assigning a function to a variable

Here I am assigning the function sum to a variable funcSum and then invoking the function.
function sum(num1, num2) {
return num1 + num2;
}

let funcSum = sum;
console.log(funcSum(10, 20));

Store function in an array

Here I am storing the function sum as the third element of the myArray and then invoking the same function by passing the first and second element from the same array.
function sum(num1, num2) {
return num1 + num2;
}

let myArray = [10, 40, sum];
console.log(myArray[2](myArray[0], myArray[1]));

Passing function as an argument to another function

Here I am passing the function innerFunc as an argument to the function outerFunc and then returning another function returnFunc.
function innerFunc(name) {
console.log(“Hello “ + name);
}

function retunFunc(name) {
return “Bye “ + name;
}

function outerFunc(myFunc, name) {
myFunc(name);
return retunFunc(name);
}

let returnVal = outerFunc(innerFunc, “Suidpta Deb”);
console.log(returnVal);
Output:
Hello Suidpta Deb
Bye Suidpta Deb

Assigning function to the property of an object

Here I am assigning the function to the property printMessage of the object employee.

var employee = {
name: “Sudipta Deb”,
printMessage: function () {
console.log(“Welcome “ + this.name);
},
};

employee.printMessage();

Arguments Object

Arguments will allow us to re-use the same function with a different set of arguments. In the below example, I am calling the same doSum() method twice, but the number of arguments is different in each scenario. Argument is a special object, which treats the list of arguments in an Array, but it is not having all the methods from Array object available to it. Read the post to understand “JavaScript Array – Everything you need to know“.

function doSum() {
let finalSum = 0;
for (let i = 0; i < arguments.length; i++) {
finalSum += arguments[i];
}
console.log(“Final Sum: “ + finalSum);
}

doSum(100, 200, 300, 400);
doSum(100, 200);

Understand Function Scope

Understanding of function scope is very important as it will explain the life span of variables within a function. I will explain this with some examples –
function sayHi() {
let name = “Sudipta Deb”;
}

sayHi();
console.log(name); //ReferenceError

If I execute the above code, I will get ReferenceError. The reason is that the variable name is defied with a function block and thus having function scope. The moment the function execution completes, that variable is no longer available. That is why when I am trying to refer the same variable in console.log, it is throwing me the ReferenceError.

Let’s change the function as shown below. This time Hello Sudipta Deb will be printed from the nested function even though the variable is declared outside the nested function. So what happening here is, when the code is trying to refer to the variable name inside the nested function, it is not able to find the variable, so it will try to find the same in the parent function. This process continues until it finds the variable, otherwise, it will show ReferenceError.

function sayHi() {
let name = “Sudipta Deb”;
let sayHello = function () {
console.log(“Hello “ + name);
};
sayHello();
}

sayHi();    //Hello Sudipta Deb


Let’s see another example. Here I am using the same variable name in the nested function, but that variable will become out of scope the moment execution of the nested function is over. That is why within the nested function, name is printing different value compared to when name is referenced in outside function.
function sayHi() {
let name = “Sudipta Deb”;
let sayHello = function () {
let name = “My name is Sudipta Deb”;
console.log(“Nested function: “ + name); //Nested function: My name is Sudipta Deb
};
sayHello();
console.log(“Outside function: “ + name); //Outside function: Sudipta Deb
}

sayHi();

But if we override the variable name by not using let inside the nested function, we will get the same result in the both the console statements as shown below –
function sayHi() {
let name = “Sudipta Deb”;
let sayHello = function () {
name = “My name is Sudipta Deb”;
console.log(“Nested function: “ + name); //Nested function: My name is Sudipta Deb
};
sayHello();
console.log(“Outside function: “ + name); //Outside function: My name is Sudipta Deb
}

sayHi();

Understand Block Scope

Block is the portion of the code written in between curly braces i.e. {}. Block scope is the scope of the variables declared within curly braces i.e. within if statement, while statement, for loop, or any set of curly braces other than a function. Note – Variables declared with the var keyword or within function declarations DO NOT have block scope.

Let’s go through some examples –
let country = “India”;
if (country === “India”) {
let capital = “New Delhi”;
}

console.log(capital); //ReferenceError: capital is not defined

I will get ReferenceError when trying to access the variable capital. The reason behind this is that capital is defined within the curly braces of the if statement, so the moment execution of if completes, the variable is out of scope.
If I replace the variable declaration from let to var like shown below, I am not getting the error anymore. That means by declaring a variable with var will not associate block scope with that variable and that is the reason to declare a variable with let always and not with var.
let country = “India”;
if (country === “India”) {
var capital = “New Delhi”;
}

console.log(capital); //New Delhi

Now let’s modify the code a little bit as shown below –
let country = “India”;
let capital = “NA”;
if (country === “India”) {
let capital = “New Delhi”;
console.log(capital); //New Delhi
}

console.log(capital); //NA

This time we are declaring the variable with the same name within the if statement and that is why the console log within the if statement is printing New Delhi, but the moment if statement execution completes, that variable becomes out of scope. That is why the last console log is printing NA, which is the value before the if statement execution started.

To understand the scope in details, please read my post below –

Immediately Invoked Function Expression (IIFE)

Before I start explaining this one, let’s understand two key parts –
Function Expression – This means defining a function and then assigning it to a variable.
Immediately Invoked – This means invoking function right away where it’s defined.
(function () {
console.log(“Hello World”); //Hello World
})();
I hope with this post you have a clear understanding of –
  • What functions are in JavaScript?
  • How functions are declared and invoked?
  • What are function scope and block scope?
  • What is “Immediately Invoked Function Expression”?


Video


Further Study



Hello