Introduction

Hoisting is a unique behavior in JavaScript that allows variables and functions to be used before they are declared in the code. Understanding hoisting can help you write more predictable and bug-free JavaScript code. This blog will cover the concepts of variable hoisting and function hoisting in detail.

Variable Hoisting

In JavaScript, variable declarations (but not their initializations) are "hoisted" to the top of their containing scope. This means that variables can be referenced before they are declared, but their values will be undefined until the line where they are assigned a value is executed.

var Hoisting

Variables declared with var are hoisted to the top of their function or global scope.

console.log(myVar); // Output: undefined
var myVar = 'Hello, world!';
console.log(myVar); // Output: Hello, world!

In this example, the declaration var myVar; is hoisted to the top of the scope, but the assignment myVar = 'Hello, world!'; remains in place. Therefore, myVar is undefined when first logged.

let and const Hoisting

Variables declared with let and const are also hoisted, but they are not initialized. This means they cannot be accessed before their declaration in the code. Accessing them before declaration results in a ReferenceError.

console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization
let myLet = 'Hello, world!';
console.log(myLet); // Output: Hello, world!
console.log(myConst); // ReferenceError: Cannot access 'myConst' before initialization
const myConst = 'Hello, world!';
console.log(myConst); // Output: Hello, world!

In these examples, attempting to access myLet or myConst before they are declared results in a ReferenceError because let and const are hoisted but not initialized.

Function Hoisting

Function declarations in JavaScript are hoisted to the top of their containing scope. This means that functions can be called before they are declared in the code.

Function Declarations

Function declarations are fully hoisted, meaning the entire function definition is moved to the top of the scope. As a result, you can call the function before its declaration in the code.

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

function sayHello() {
  console.log('Hello, world!');
}