Skip to main content

What is Hoisting?

When you're writing JavaScript code, you might encounter a behavior called "hoisting" It sounds complex, but it's actually quite simple once you understand it.

What is Hoisting?

Hoisting is JavaScript's way of moving function declarations and variable declarations to the top of their containing scope during the compilation phase.

This means you can call a function or use a variable before it's even declared in your code!

Function Hoisting:

Function declarations are hoisted to the top of their containing scope. This means you can call a function before it's declared in your code, and JavaScript won't throw an error.

Example:

sayHello(); // Output: Hello!

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

Even though sayHello() is called before its declaration, JavaScript doesn't throw an error. That's because the function declaration is hoisted to the top of its scope.

Variable Hoisting:

Variable declarations using the var keyword are also hoisted to the top of their containing scope. However, only the declaration is hoisted, not the initialization.

Example:

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

var x = 10;

In this example, x is hoisted to the top of its scope, but its value is undefined until it's explicitly assigned later in the code.

Limitations:

It's important to note that hoisting only applies to function declarations and variable declarations using var, not variable declarations using let or const.

Variables declared with let or const are not hoisted, and trying to access them before their declaration will result in a ReferenceError.

Conclusion:

Understanding hoisting can help you write cleaner and more organized JavaScript code. Just remember that function declarations and variable declarations using var are hoisted to the top of their scope, while variables declared with let or const are not.