techStackGuru

JavaScript Hoisting


Hoisting in JavaScript refers to the moving of variables and functions to the top of their containing scope during compilation. Thus, variables and functions are treated as if they were declared at the beginning regardless of where they appear in the code.

Both function and variable declarations are subject to hoisting, but they are treated differently.

Variable Hoisting:

console.log(a); // undefined
var a = 9;
console.log(a); // 9 

With the var keyword, variables are declared at the top of their scope, but not their assignment. This will allow you to access the variable before it appears in the code, as the variable declaration will be at the top of the code. The value assignment remains in its original position, however. Accessing the variable before its value is assigned will result in an undefined value.

Hoisting variables is allowed with var, but not let and const.

Hoisting

a = 9;
console.log(a); // 9
var a;  

ReferenceError

a = 9;
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a;  

SyntaxError

a = 9;
console.log(a); // SyntaxError: Missing initializer in const declaration
const a;  

JavaScript, on the other hand, does not hoist initializations.

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

undefined

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

Function Hoisting:

ReferenceError

check();
let check = function() {
  console.log('Hello'); // ReferenceError: Cannot access 'check' before initialization
} 

Attempting to invoke check() before it has been defined causes this error. A function expression is not hoisted like a function declaration in JavaScript. As a result, an error occurs if you attempt to call check() before the function expression has been assigned to check.

This can be fixed by moving the function expression above the function invocation, or by changing the declaration to a function declaration.

check();
function check() {
  console.log('Hello'); // Hello
} 

Can be used after declaration

let check = function() {
  console.log('Hello'); // Hello
};
check(); 

Function hoisting taking precedence over variable hoisting

hoistedFunction();

var hoistedFunction = function() {
  console.log('This function was hoisted as an expression.'); // will not run
};

function hoistedFunction() {
  console.log('This function was hoisted as a declaration.'); // will run
} 

As you can see in the examples, function declarations, along with their bodies, are hoisted entirely, whereas variable declarations (with var), however, are initialized with undefined.