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); // prints: undefined
var name = "Paul";
console.log(name); // prints: Paul

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(); // prints: Hello World!

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

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(editor); // Uncaught ReferenceError: editor is not defined
let editor = "Paul";

In the above example, since editor 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.