Variable and Function Hoisting in Javascript

js.Srijan

Introduction

In general, you declare functions and variables before you use them in your program. For example, we declared addTwo function before we called it in the code. Example:

function addTwo(x){
	return x+2;
}

//Output: 4
addTwo(2);

But in javascript, the functions and variables can be called before they are declared in the program. This concept is called hoisting.

//Output: 4
addTwo(2);

function addTwo(x){
	return x+2;
}

In the above example, addTwo is called before it is declared, but it returned the same value 4 instead of undefined. What exactly happened in the above example? Is the declaration being moved to the start of the code? It appeared as if declarations has been moved to the start of the program.

No, but the answer is quite simple, keep reading...

During compilation, the javascript engine first reads the function and variable declarations and put them into the memory. For this reason, during the program execution, they are accessible and can be used before they are declared in the program. Thus, appearing as if the declarations have been moved to the starting of the program magically.

Function and variables declared anywhere in the file are available for the use at the very top of the file. This behavior is called hoisting.

Variable Hoisting

Let's consider below example,

//Output: undefined
console.log(test);

var test = 3;

//Output: 3
console.log(test);

You would have thought that the first console.log should have given 3 as the output. But instead console.log(test) resulted in undefined because only declarations are hoisted to the starting of the program and not initializations. For more clarity, let's expand the above example,

Declarations are hoisted to the starting of the program and not the initializations.

//Output: undefined
console.log(test);

var test;
test = 3;

//Output: 3
console.log(test);

Here, var test; is moved to the start of the program and the assignment to 3 happened after the execution of the first console.log. For this reason, the output of the first console.log is undefined.

Best Practice

Hoisting can create some confusion in declaring variables and functions, therefore it is considered best practice to declare all variables in starting of the program.

What about let and const?

Are variables declared using let and const are not hoisted? We will discuss hoisting in case of let and const in the next article.


We publish articles on web development and technology frequently. Consider subscribing to our newsletter or follow us on our social channels (twitter, Facebook, LinkedIn).

Share and support us

Share on social media and help us reach more people