What is hoisting in Javascript?

Coccagerman
2 min readJun 3, 2021

Hoisting was thought up as a general way of thinking about how execution contexts (specifically the creation and execution phases) work in JavaScript. However, the concept can be a little confusing at first.

Conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.

One of the advantages of JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code. For example:

function catName(name) {
console.log("My cat's name is " + name);
}
/*
The result of the code above is: "My cat's name is Chloe"
*/

Even though we call the function in our code first, before the function is written, the code still works. This is because of how context execution works in JavaScript.

Hoisting works well with other data types and variables. The variables can be initialized and used before they are declared.

Only declarations are hoisted

JavaScript only hoists declarations, not initializations. If a variable is declared and initialized after using it, the value will be undefined. For example:

console.log(num); // Returns undefined, as only declaration was hoisted, no initialization has happened at this stage
var num; // Declaration
num = 6; // Initialization

The example below only has initialization. No hoisting happens so trying to read the variable results in ReferenceError exception.

console.log(num); // Throws ReferenceError exception
num = 6; // Initialization

Initializations using let and const are also not hoisted.

// Example with let:
a = 1; // initialization.
let a; // Throws ReferenceError: Cannot access 'a' before initialization
// Example with const:
a = 1; // initialization.
const a; // Throws SyntaxError: Missing initializer in const declaration

Two concepts are essential:
- Functions always move up in their scope. Therefore, we can choose where to declare and use them.
- The declaration of variables moves up in their scope, but not the assignment. Before using a variable, it must be created and assigned.

--

--