Ketan Jadhav

Closures in JavaScript

By Ketan Jadhav

Last updated cal_iconDecember 2, 2022

According to the internet, javascript is an object-oriented programming language commonly used to create interactive effects within web browsers.

Many of us use javascript in our day to day life, but we never paid attention to concepts of it. JavaScript closures are one of those concepts that many people have trouble understanding.

Closures in javascript

If you want to save yourself from the so-called monsters of JavaScript, you must understand how it works. I’ll explain what a closure is in clear terms and relate it to a real-life example to make it easier to remember.

So, What is Closure?

A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables.

Let’s understand it using below code snippet:

Lets understand it using below code snippet

Here we have two functions:

  • An outerFunc with variable f_name and returning innerFunc.
  • An innerFunc with its variable l_name and also accessing outerFunc variable f_name.

      

The scope of variable  f_name  is limited to the  outerFunc  function, and the scope of a variable  l_name  is limited to the  innerFunc  function.

Now, what happened when this line of code was executed.

 var getName = outerFunc(); 

 getName();

Result of outerFunc() gets stored in a variable called getName and now is a function type.

And, Now comes the interesting part.

When getName() function gets executed:

  • It creates a variable called l_name and assigns a value John to it.
  • Now, javascript try to execute  console.log(“Name: “, f_name, l_name); , javascript knows that l_name variable is exist as it is just now created, but f_name is no longer existed because f_name is a part of outerFunc() and it will only exist if outerFunc() is in execution. So here f_name is no longer exists.

   

Then how will we get the f_name variable?

The answer is Closure!, yes you heard it right.

During the execution of the  parent   function, it passes its scope chain to the  child  function, and in this way, the  child  can access the variables that are preserved(closure) in the preserved variable.

So, our innerFunc() will preserve the variable  f_name=”John”  when the outerFunc() is implemented and kept holding it.

Now, on execution of  getName  function(child function), it has its own scope now, and scope also contains variable f_name because it has preserved variable within its own closure(scope) at the execution of parent function.

In this way, Javascript knows  f_name = “John”  and  l_name = “Washington”  , and we will get output as:  Name:  John Washington.

Closure stores the references of variables of outer function.

Hurrey!Now you have completely understood what closure is in javascript.

Hurrey!Now you have completely understood what closure is in javascript.

Conclusion:

Closures are one of those concepts in javascript which is difficult to understand at the beginning, But one if you understand it carefully, it isn’t that bad or difficult.

Closures will allow us to access the variables and functions even after the execution of those functions has done.

Get In Touch

How Can We Help ?

We make your product happen. Our dynamic, robust and scalable solutions help you drive value at the greatest speed in the market

We specialize in full-stack software & web app development with a key focus on JavaScript, Kubernetes and Microservices
Your path to drive 360° value starts from here
Enhance your market & geographic reach by partnering with NodeXperts

Shashank Baranawal

Hoisting in JavaScript

By Shashank Baranawal

Last updated cal_iconNovember 28, 2022

Let’s talk about hoisting in JavaScript, how it works and how we can benefit from it.

Hoisting in JavaScript

JavaScript’s another beautiful part that makes us love language.

So, let’s start with this :

What is Hoisting in JavaScript?

In simple and easy words hoisting in javascript means hosting is the action of moving all the variable and function declarations of the javascript interpreter to the top of the current scope before the code execution. It allows us to access the variables and functions anywhere in their scope, no matter where they are declared.

We will see various examples below that will help us better understand the Variable and function hoisting behavior of JavaScript.

In this article we will talk about:

  • Hoisting Variable
  • Hoisting Functions

Before moving on to hoisting, you must know undeclared variables do not exist until the code assigning them is executed.

All undeclared variables are global variables.

Hoisting Variable ?

The scope of a variable declared with the keyword var is its current execution context. This is either the enclosing function or for variables declared outside any function, global.

Consider the below piece of code and let’s see what the output would be.

Javascript hoists our variable language to the top of the file and declares is there but it does not set it equal to anything, then as the interpreter moves through the file to where the variable was initially declared and sets the variable equal to the correct value which is javascript.

Output:-

You can see our first console log was undefined and the second console log was the value javascript since it ran through the file and set the language variable equal to javascript.

Note? : Although it seems that the declaration has moved up in the program in hoisting, what happens here is that the function and variable declarations are added to memory during the compile phase.

When the variable is declared inside the function, it will be hoisted at the top of the function, see the below example.

Out Put

Output:-

Out put

We get a reference error when we try to access a topic variable in the console statement outside the function because the variable topic is hoisted at the top of the greet function instead of the top of the program, and it becomes a local variable instead of the global variable.

Variables declared with let and const remain uninitialized at the beginning of execution while variables declared with var are initialized with a value of undefined.

Hoisting Function?

Same as variable declarations are hoisted and moved to the top, functions that are declared also get hoisted.

get hosted

 

Output:-

Get hoisted

We have called the helloHoisting() function before its declaration and get the desired output due to hoisting, the program is executed as follows:

Output

function declaration is moved to the top due to hoisting!

However it we use functions as an expression then it’s not hoisted because be it variable or function hoisting it only works with var keyword, see below:

with var keyword

Output:- ReferenceError: Cannot access ‘sayHello’ before initialization

Reference Error

ES6: let Keyword

let Keyword

Output:-

let Keyword output

As before, for the var keyword, we expect the output to be undefined. But this time we got a reference error. Does that mean let and const variables were not hoisted? The answer is that variables declared with let are still hoisted, but not initialized, inside their nearest enclosing block. If we try to access it before initialization, it will throw a Reference Error.

Conclusion?:

Hoisting is the default behavior of JavaScript that enables us to access variables and functions before their declaration. Hoisting works with var keyword and not let and const keywords, just the declarations are hoisted and not the initialization. If a variable is declared inside the function it will be hoisted at the top of the function and not at the global scope level. Functions are hoisted too, but functions as an expression are not.

 

Get In Touch

How Can We Help ?

We make your product happen. Our dynamic, robust and scalable solutions help you drive value at the greatest speed in the market

We specialize in full-stack software & web app development with a key focus on JavaScript, Kubernetes and Microservices
Your path to drive 360° value starts from here
Enhance your market & geographic reach by partnering with NodeXperts