Skip to main content

Hoisting

YOU CAN SKIP FOR NOW IF YOU DON'T UNDERSTAND

don't necessarily need it for leetcode

Hoisting in Detail!

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

This means that regardless of where variables and functions are declared in your code, they are actually moved to the top of their scope.

Let's break down hoisting in more detail:

Variable Hoisting (var)

  • Variables declared with var are hoisted to the top of their function scope or global scope.
  • The value is initialized to undefined.
  • However, assignment of value only happens when it reaches the assignment code.

Example:

console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5

In the above example, var x is hoisted to the top of the scope, so console.log(x) does not result in an error.

However, x is still undefined until the actual assignment (var x = 5) is reached during execution.

Variable Hoisting (let and const)

Variables declared with let and const are hoisted to the top of their block scope (inside the block they are declared in), but they are not initialized at all.

This is known as the "temporal dead zone" (TDZ).

Attempting to access these variables before they are declared and initialized in the code will result in a reference error.

console.log(x); // Error: Cannot access 'x' before initialization
let x = 5;

Function Hoisting - Regular Functions

Function declarations are also hoisted to the top of their containing scope.

This means you can call a function before it's declared in the code, and JavaScript will still recognize it.

Example:

sayHello(); // Output: 'Hello!'

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

In this example, the function sayHello() is called before its declaration, but it still works because the function declaration is hoisted to the top.

Function Hoisting - Arrow Functions

Arrow functions, unlike traditional function declarations, are not hoisted.

Attempting to call an arrow function before it's declared in the code will result in a reference error.

Example:

myFunction(); // Error: myFunction is not defined

const myFunction = () => {
console.log('Hello!');
};

In this example, calling myFunction() before its declaration results in a reference error because arrow functions are not hoisted.