JavaScript Hoisting

In this tutorial, we will learn about JavaScript variable hoisting and function hoisting. Before we do that, let’s brush up on variable declaration and initialization.

Declaration of variable: When we declare variable, we tell the compiler about the name of the variable that we are going to use. In JavaScript we declare variable using var keyword.

var a;

Initialization of variable: The process of assigning value to variable is called as initialization of variable. For e.g. a=5. We can also declare and initialize variable at the same time, which is very common practice by programmers.

var a=5;

JavaScript variable hoisting

To understand hoisting concept we will consider different cases based on declarations and initialization of variable.

Case 1: Declare and initialize variable before using it.

var a;
a=5;
console.log(a+2);
//output: 7

Usually this approach is used by many people in programming. We declare and initialize variable and then we use it. Here we get expected output i.e. 5+2=7.

Case 2: Initialize and use variable before declaring it.

a=5;
console.log(a+2);
var a;
//Output: 7

In case 2, instead of raising an error it gives an output 7. Here we declare variable ‘a’ after assigning value and using it. JavaScript allows us to declare a variable anywhere in given scope, irrespective of its initialization and use. This is known as JavaScript hoisting.

Definition: The mechanism of moving declarations of variables or functions to the top of their scope is called as JavaScript hoisting.

Case 3: Use variable before initializing it

var a;
console.log(a);
a=5;
//Output: undefined

In case 3, we get an error undefined. That means, Javascript will not move initialization of variable to the top of their scope. JavaScript hoisting is about moving declaration of variable only and not initialization. In simple language, you can’t use variable before initializing it.

Case 4: Scope in JavaScript Hoisting

It is always recommended to declare variable at the top of their respective scope. Otherwise if two variables of same name exists in both global and local scope without any kind of declaration, the changes in value of global scope variable will get reflected in local scope and vice versa. To understand this, see the following code snippet.

 x=5;
function test(){
console.log(x+10);
x=6;
console.log(x);
}
test();
console.log(x);
//Output: 15 6 6

In above example, variable x exists outside function test() as well as inside. the first console.log statement will access global variable x which has value 5 and will return value 5+10 i.e. 15. Now on line 4, it seems that we are initializing local variable x=6, but actually we are overriding global variable x which had value 15 previously. Hence next console.log statement will return value 6, when we call test() function on line 7. Since, this changes are made into global variable the last console.log statement will return value 6.

To avoid this overriding, we have to declare variable x inside function test(). Now that we are familiar with variable hoisting concept, why not use it here?

x=5;
function test(){
console.log(x+10);
x=6;
console.log(x);
var x;
}
test();
console.log(x);
//Output: NaN 6 5

The only change we did here is declaring variable x inside function test() at last line. Now we have 2 different variables with same name. One is within function scope. and other one is in global scope. Take a look at output. The first console.log statement raises an error called NaN (Not a Number). Read more about NaN here. This is because we have not initialized x yet which is similar to case 3. The next console.log statement after initialization of x returns value 6. The last console.log statement is interesting. It returns value 5. Whatever changes we made inside function test didn’t affect the global variable x. This is because we made all the changes with respect to function scope and not global scope.

JavaScript function hoisting

Time to brush up basic terms! First we will see what is function declaration and function expression in JavaScript.

Function Declaration: The syntax for function declaration is as follows:

function function_name(){
//body
}

Here you define your function along with name of your function. You need to call this function later to use it as part of your program.

Remember! In JavaScript, we don’t treat function declaration and function definition as two different things. We actually define function by including function body and call it as a function declaration. So don’t get confused. From JavaScript perspective, declaration and definition are one and the same.

Function Expression: In function expression we assign function to a variable. The main difference between function expression and declaration is that you can omit function name and use it as anonymous function. The syntax of function expression is as follows:

var function_name = function(){
//body
}

Function hoisting hoists the function definition itself. That means JavaScript allows you to use function before its actual definition.

Case 1: Using function after its declaration.

function test(){
console.log(“This is test function”);
}
test();//output: This is test function

Case 2: Using function before its declaration.

test();function test(){
console.log (“This is test function”);
}
//Output: This is test function

Looking at case 1 and 2 we can say that JavaScript allows function hoisting. But there is a catch. JavaScript does not allow hoisting in case of function expressions.

Case 3: Using function before its expression

test();var test = function(){
console.log(“This is test function”)
}
//Output: Uncaught TypeError: test is not a function

Above code will raise an error. The way JavaScript interprets this code is somewhat different. Here declaration of variable test is hoisted, which is same as variable hoisting. But assignment of anonymous function to test variable is done when interpreter reaches to the line where we have written function expression. Since we are calling test() before assignment, It gives TypeError stating that test is not function.

Overall, JavaScript variable hoisting and function hoisting both work in same manner. Interpreter moves declaration of variable and function to the top of their scope. But initializations of variables and function expressions are not moved. Declaring variables and functions by yourself before using them is considered as good practice.

Thank you for reading!

--

--