Javascript Hoisting

Gunjeev Singh
Last Updated: May 13, 2022

Introduction

Javascript Hoisting is one of Javascript's trademark features, which sets it apart from other programming languages. Knowing how Javascript hoisting works and how we can utilize its capabilities is necessary for being a good Javascript developer, one of the most hired job profiles. In this blog, we will look at the concept of Javascript hoisting and how it differently affects various variables.

Before we start learning about Javascript hoisting, it is essential to understand the different types of variables available to us in Javascript(JS). It is necessary to know how various variables get hoisted in Javascript. 

Variables in Javascript

Variables are nothing but named memory locations. In most languages, variables are defined and initialized with their data type and their name. An example for this is:

// A variable named n with data type int is initialized
int n = 100 

 

Unlike this standard, in Javascript, variables can be three types: var, let, and const. These variable types can hold all kinds of data supported by the JS engine. They are initialized in Javascript as:

 

// Creates a variable of type var@var new = "word";@@// Creates a variable of type let@let new = "word";@@// Creates a variable of type const @const new = "word";

Difference Between Var, Let, and Const

You may be wondering why we need three different types of variables when they can store the same data? Here's the catch - "var" was a type which the ES5 engine supported; the issue with var was that it could be re-declared, as well as updated, like:

 

var first = "first_variablei";
var first = "first_second_variable";

// And also like :
var first = "first_variable";
first = "first_second_variable";

 

A problem arises when re-declarations and updates create bugs with exceeding lines of code.

This problem is solved by 'let,' a block-scoped variable that we cannot re-declare like var.

Const is also a block-scoped variable that we cannot update either.

 

// With let:
let first = "first_variable";
first = "two"; // Allowed
let first = "three"; // Javascript engine throws an error

// With const:
const first = "first_variable";
first = "two"; // Javascript engine throws an error
const first = "three"; // Javascript engine throws an error

 

Now that we have a basic understanding of variable types in Javascript, we can now move on to JavaScript hoisting. However, this knowledge of variables might not be comprehensive enough, so you can read this blog if you need more information.

Javascript Hoisting

Before we dive into the concepts of variable and function hoisting in Javascript, we need to have an excellent fundamental understanding of what JavaScript hoisting exactly means. Firstly, note that Javascript is an interpreted language and not a compiled one; hence, the JS engine starts the execution process when we execute some Javascript code. This process is divided into two parts, creation and execution. In the first part of creation, the Javascript engine takes your variables and functions and places them at the top of their scope. This very process of putting the variables at the top is hoisting. 

In hoisting, though it seems that the declaration has moved up in the program, the actual thing that happens is that the function and variable declarations are added to memory during the creation phase.

Variable Hoisting

Earlier in this blog, we discussed how a significant difference between the different variable types in Javascript is in their hoisting mechanism; hence, let us break down the hoisting of variables into variable types. 

1. "Var" Keyword: When variables are declared with the "var" keyword, on execution, the Javascript engine places them at the top of the script. Let us understand this with the help of an example:

 

console.log(name);
var name = "Gunjeev";

 

Please note that the variable 'name' is defined after it is being used. Despite this, the engine would not throw an error. It would instead display:

 

undefined


When the Javascript engine hoists the variable, i.e., places the variable at the top of the code and initializes it with the value "undefined."This means that the code used in the example essentially is the same as

 

var name;
console.log(name); // Gives output undefined
name = "Gunjeev";

 

2. "Let" Keyword: The difference between the var and let keywords in JavaScript  hoisting terminology is just that the Javascript engine puts the var variables at the top of the code and also initializes them with the value "undefined."But, in the case of the "let" keyword, the JS engine only moves the declaration to the top and does not initialize the value. Hence, the same example with the let keyword would be as follows:

 

console.log(name);
let name = "Gunjeev";

 

Thie code above would throw an error on the console, which would say that you cannot use a variable without initializing it.

ReferenceError: Cannot access 'name' before initialization

 

Please note that this is not the same error that the console throws when a variable that is not defined is used and called. An undefined error occurs when a variable is either not defined or explicitly defined as type undefined. ReferenceError is thrown when trying to access a previously undeclared variable.

Note: Hoisting works the same way for both let and const variables.

Function Hoisting

Functions are hoisted similar to variables. At the creation phase of the execution process, function declarations are shifted to the top of the code. More precisely, what the javascript engine does is that it creates an object of every function, and places that object in the heap memory, and then creates a reference (a pointer) to this function and places it in the stack. 

An example of function hoisting could be:

 

let a = 10, b = 5;

let sum = add(x,y);
console.log(sum);

function add(x, y){
return x + y;
}

 

Now in this example, we have called the function add() without declaring it. This does not show an error because of function hoisting. The code above is, in a sense, equivalent to:

 

function add(x, y){
    return x + y;
}

let a = 10, b = 5;

let sum = add(a,b);
console.log(sum);

 

We should note here that arrow functions throw an error while they are hosted, as they are not functions but are essentially function expressions. The engine hence initializes them like variables, with "undefined," which means that when they are called in the code, they do not represent functions, which throws an error:

 

let a = 10,
    b = 5;

let sum = add(a,b);
console.log(sum);

var add = (a, b) => a + b;

 

This throws an error like:

 

TypeError: add is not a function

Frequently Asked Questions

  1. Why are some functions not hoisted?
    Functions that are declared as expressions do not get hoisted. This is because the Javascript Engine considers them as variables and initializes them as undefined. When they are called, they throw undefined, which throws an error in turn.
  2. When does the engine start the JavaScript hoisting process?
    The Javascript engine hoists variables and functions in the creation phase of the execution process.

Key Takeaways

In this blog, we learned that Javascript has three different types of variables, and a significant difference is how the engine hoists them. Hoisting is a property of Javascript that puts variables at the top of their scope when the execution starts. 

If you want to learn more about javascript, you can visit our guided path here.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think