Back to all posts

Demystifying JavaScript Hoisting: How JavaScript Declarations are Hoisted


Hoisting in JavaScript is a behavior in which a function or a variable can be used before declaration. For example,

// using test before declaring
console.log(test);   // undefined
var test;

This code behaves as

var test;
console.log(test); // undefined

How this works

During the compilation phase, JavaScript splits the code into two steps:

  • The creation phase
    In the creation phase, the JavaScript engine scans through the code and identifies variable and function declarations. It allocates memory for variables and creates references for functions.
  • The execution phase.

Variable Hoisting

in terms of variables and code constants, keyword var is hoisted and let and const does not allow hoisting.

It’s important to note that only the declarations are hoisted, not the initialization or assignments.

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

Function Hoisting

A function can be called before declaring it. For example,

// program to print the text
greet();

function greet() {
    console.log('Hi, there.'); //output: Hi, there.
}

Understanding function hoisting helps us write code where functions can be defined and invoked in any order within their scope, providing flexibility in organizing our code. However, it’s still considered a best practice to declare functions before invoking them to enhance code readability and maintainability.