JavaScript Hoisting

Sekou Dosso
The Startup
Published in
3 min readSep 7, 2020

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

Hoisting is JavaScript’s default behavior of moving declarations to the top.

JavaScript Declarations are Hoisted

In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared.

result => 5
result => 5

To understand this, you have to understand the term “hoisting”.

Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

The let and const Keywords

In JavaScript, a ReferenceError is thrown when trying to access a previously undeclared variable.

Variables defined with let and const are hoisted to the top of the block, but not initialized.

Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared.

Using a let or const variable before it is declared will result in a ReferenceError.

The variable is in a “temporal dead zone” from the start of the block until it is declared:

JavaScript Initializations are Not Hoisted

JavaScript only hoists declarations, not initializations.

Example 1 does not give the same result as Example 2:

Result => 5 7

var

The scope of a variable declared with the keyword var is its current execution context. This is either the enclosing function or for variables declared outside any function, global.

Result => x is 5 and y is undefined

This is what really happened here.

Does it make sense that y is undefined in the last example?

This is because only the declaration (var y), not the initialization (=7) is hoisted to the top.

Because of hoisting, y has been declared before it is used, but because initialization are not hoisted, the value of y is undefined.

Example 2 is the same as writing:

Result => 5 undefined

Declare Your Variables At the Top!

Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.

If a developer doesn’t understand hoisting, programs may contain bugs (errors).

To avoid bugs, always declare all variables at the beginning of every scope.

Since this is how JavaScript interprets the code, it is always a good rule.

--

--