JavaScript Hoisting

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed.

This phenomenon can sometimes lead to unexpected behavior if not understood properly.

Let's explore hoisting in more detail with code examples:

Hoisting with Variable Declarations

Variable declarations are hoisted to the top of their scope, but not their initializations.


console.log(x); // Output: undefined

var x = 5;

console.log(x); // Output: 5

In the above example, the variable xis hoisted to the top of its scope, resulting in the first console.log(x)statement printing undefined.

The assignment var x = 5;is not hoisted, so xremains undefineduntil it's assigned the value 5.

Example


console.log(x); // Output: undefined

var x = 5;

console.log(x); // Output: 5

Hoisting with Function Declarations

Function declarations are fully hoisted, including their definitions.


sayHello(); // Output: "Hello, world!"

function sayHello(){ 
  console.log("Hello, World!" );
}

In the above example, the function sayHello()is hoisted to the top of its scope, allowing it to be invoked before its actual declaration in the code.

Example


sayHello(); // Output: "Hello, world!"

function sayHello(){ 
  console.log("Hello, World!" );
}

Hoisting with Function Expressions

Function expressions, unlike function declarations, are not hoisted in their entirety.


sayHello(); // Output: TypeError: sayHello is not a function

var sayHello = function(){ 
  console.log("Hello, World!" );
}

In the above example, only the variable declaration var sayHello;is hoisted, not the function expression function(){ ... }. Therefore, attempting to invoke sayHello();before the function expression assignment results in a TypeError.

Example


sayHello(); // Output: TypeError: sayHello is not a function

var sayHello = function(){ 
  console.log("Hello, World!" );
}

Hoisting within Nested Scopes

Hoisting also occurs within nested function scopes.


function outer(){ 
  console.log(inner);// Output: undefined
  
  var inner = "I'm inside!";
  console.log(inner);

}

outer();

In the above example, Even though inneris declared within the outer()function, its declaration is hoisted to the top of the function scope.

Example


function outer(){ 
  console.log(inner);// Output: undefined
  
  var inner = "I'm inside!";
  console.log(inner);

}

outer();