What Is Hoisting Data Structure?


Angela Bailey

What Is Hoisting Data Structure?

In JavaScript, hoisting refers to the behavior of moving variable and function declarations to the top of their containing scope during the compilation phase. This means that regardless of where variables and functions are declared in your code, they are interpreted as if they were declared at the beginning of their respective scopes.

Variable Hoisting:

JavaScript variables can be declared using the var keyword. When a variable is hoisted, its declaration is moved to the top of its scope.

However, only the declaration is hoisted, not the initialization. Let’s take a look at an example:

console.log(num); // Output: undefined
var num = 10;
console.log(num); // Output: 10

In this example, even though num is logged before it is assigned a value, it doesn’t throw an error. This behavior is because during hoisting, the declaration of num is moved to the top of its scope and assigned a default value of undefined.

Therefore, when we log num before assigning it a value, it outputs undefined.

Function Hoisting:

Similar to variable hoisting, function declarations are also hoisted to the top of their containing scope. This means that you can call a function before it appears in your code. Consider this example:


function sayHello() {

In this case, we invoke the sayHello() function before it’s defined, but it still works. This is because during hoisting, the function declaration is moved to the top of its scope, allowing us to call it anywhere within that scope.

Hoisting and Scoping:

It’s important to note that hoisting only moves the declarations to the top of their respective scopes, not the assignments. Therefore, when using variables or functions, it’s best practice to declare and initialize them at the beginning of your code or their containing scopes.

Additionally, hoisted variables are scoped to their containing function or global scope. If a variable is declared inside a block statement (e.g., if statement or for loop), it will still be hoisted but its scope will be limited to that block.


Hoisting is a fundamental concept in JavaScript that allows you to use variables and functions before they are declared in your code. Understanding how hoisting works can help you write more organized and readable code by declaring your variables and functions at the top of their respective scopes.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy