Monday, September 20, 2021

What is Variable and Function Hoisting in JavaScript? Example Tutorial

Hoisting is a complex concept in JavaScript. Like other major programming languages, variables and functions are an important part of JavaScript. Being a dynamically typed programming language, the variable declaration does not require specifying variable types. JavaScript also supports functions. But there is a catch. When variables and functions are declared in JavaScript, a process called hoisting takes place, and if you don't know this important concept you may struggle reading and understanding code but don't worry. In this article, I will teach you what is hoisting in JavaScript and give you real-world examples of the function and variable hoisting to start with.  


Hoisting is a bit complex to understand at first, but once you will go through examples, it is nothing but a simple behind-the-scenes process. In this article, we will discuss hoisting in JavaScript with the help of examples.

By the way, if you are a javascript beginner and looking for the best resources like online courses, books, and tutorials to learn Javascript in-depth then you can also check out my earlier post about the best JavaScript coursesbooks, and websites.

And, if you don't mind learning from free resources then I have also shared my favorite free online courses to learn JavaScript, in case you are interested in free online courses from Udemy and Coursera.  





What is hoisting in JavaScript? Example

Observe the following JavaScript code.

let a = 100;

function doubleIt(a) {

	console.log(a*2);

} 

doubleIt(a);

In the above code, first, a variable named ‘a’ is declared and 10 is assigned to it. Then, a function named ‘doubleIt’ is declared that accepts an argument and prints the double to it in the console. After that, ‘doubleIt’ is called, and ‘a’ is passed to it. This looks very simple but a lot of things are happening behind the scenes.

When this code is executed, JavaScript engines create the global execution context. This global execution context has two phases - creation and execution. 

In this creation phase, all the variable and function declarations created in the file are moved to the top of the code by the JavaScript engine. This process of moving the variable and function declarations to the top of the code during the creation phase is known as JavaScript hoisting.  

This is also one of the frequently asked JavaScript interview questions and knowing this concept can help you during interviews. 





Variables hoisting in Javascript - Example

The uplifting of variable declarations to the top of the code is known as variable hoisting. Observe the following code. 

console.log(a);
var a = 10;

Output: undefined

When the above code is executed, it does not throw any error even when variable ‘a’ is accessed before it is declared. Why so? The reason is variable hoisting. 

Behind the scenes, the above code looks like the following.

var a;

console.log(a);

a = 10;

During the creation phase, variable ‘a’ is moved to the top of the code. But you should note one important thing here: Only the declaration of ‘a’ is moved to the top of the code while its value assignment is still on the same line. 

So when the variable is moved to the top and its value assignment is left where it was, the JavaScript engine initializes it with ‘undefined’. But this initialization of the variable with undefined changes when the let keyword is used. 

console.log(a);

let a = 10;

When the above code is executed, it will throw a ‘ReferenceError’.This happens because when the hoisting of the variables declared with the let keyword is done, it does not initialize the variable’s value with anything. 

The same error occurs with the variables declared with the const keywords.






Function hoisting in JavaScript - Example

Functions are also hoisted by the JavaScript engine during the creation phase. Observe the following code. 

var a = 10;

doubleIt(a);

function doubleIt(a) {

	console.log(a*2);

} 

Output: 20

The above code executes properly even when the function is called before its declaration. This happens because the function ‘doubleIt’ is hoisted to the top of the code. 

The scenario changes when instead of normal function, function expression is used.

var a = 10;

doubleIt(a);

var doubleIt = function(a) {

	console.log(a*2);

} 

This time, the above code will throw a ‘TypeError’ stating that ‘doubleIt’ is not a function. This happens because ‘doubleIt’ is actually a variable. So the JavaScript moves this variable to the top of the code and assigns undefined to it. Thus, resulting in the error. 

The same error will occur if arrow functions are used.  

Here is a nice diagram that explains hoisting in JavaScript:

What is Variable and Function Hoisting in JavaScript? Example Tutorial


That's all about variable and function hoisting in JavaScript. In simple terms, Hoisting is a process in JavaScript that moves the variable and function declaration in the script to the top of the code. Remember, only declarations are moved to the top, not value assignments. 

If the variable is declared using var, then the undefined is assigned to it. Such assignments do not happen with the variable declared using let or const. Similarly, functions are also moved to the top of the code. But if function expressions or arrow functions are used, then it will result in an error. So this is all about hoisting. 

Other JavaScript Articles and TutorialsYou May like to explore


Thanks for reading this article so far.  If you like this JavaScript Variable and Function Hoisting tutorial and example then please share it with your friends and colleagues. If you have any questions or feedback, then, please drop a comment.

P. S. - If you want to self-learn JavaScript in-depth and need some recommendations then I also suggest you go through the best JavaScript courses. It has many hands-on courses to learn modern JavaScript features.     

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.