DEV Community

Charlie @ 90-10.dev
Charlie @ 90-10.dev

Posted on • Originally published at 90-10.dev on

Javascript Hoisting

Hoisting is a mechanism where variable and function declarations are moved to the top of their scope before code execution - regardless of where they are declared in the code, they are processed first before the code is executed.

Variable Hoisting

When a variable is declared using the var keyword, it is hoisted to the top of its scope so can be accessed and used even before it is declared in the code. But, its value will be undefined until assigned a value.

console.log(name); // Output: undefined
var name = "Paul";
console.log(name); // Output: Paul

Enter fullscreen mode Exit fullscreen mode

Function Hoisting

Functions declared using the function keyword are also hoisted to the top of their scope so can be called before they are declared in the code:

sayHello(); // Output: Hello World!

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

Enter fullscreen mode Exit fullscreen mode

Hoisting in ES6

ES6 introduced the let and const keywords for declaring variables. Unlike variables declared using var, variables declared using let and const are not hoisted to the top of their scope, therefore cannot be accessible before declaration.

console.log(name); // Output: Uncaught ReferenceError: name is not defined
let name = "Paul";
Enter fullscreen mode Exit fullscreen mode

In the above example, since name is declared using let, it is not hoisted to the top of its scope, so it results in a ReferenceError.

Take Away

It is recommended to use let or const instead of var to avoid hoisting-related issues.

Top comments (0)