Image of a cloud

Cloud Coding

Variable Hoisting in JS

By: Tristan Pedersen

Variable Hoisting in JS

Hoisiting is JavaScript's main behavior for moving declarations to the top. A variable can be declared after it has been used.

For example, you should understand code like this:

x = 4;
elem = document.getElementById("example");
elem.innerHTML = x;
var x;

Hoisting is the default behavior of moving all declarations to the top of the current scope (current script or function). Variables with let and const are hoisted to the top of the block, but not initialized. This means the block using a let variable before it is declared will result in a RefferenceError. The variable is in a "temporal dead zone" from the start of the block until it's declared.

For example:

carName = "Toyota";
let carName;

This would result in a RefferenceError.

Using a const variable before it's declared is a syntax error, so the code will not run.

For example:

carName = "Toyota";
const carName;

JavaScript only hoists declarations, but does not initialize them.

For example:

var x = 5;
elem = document.getElementById("example");
elem.innerHTML = x + y;
var y = 7;

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

This would be the same as writing:

var x = 5;
var y;
elem = document.getElementById("example");
elem.innerHTML = x + y;
y = 7;

Summary: Hoisting (to many developers) is an unknown or overlooked behavior of JavaScript. If a developer doesn't understand hoisting, programs may contain bugs. To avoid bugs always declare all variables at the beginning of every scope; since this is how JavaScript will interpret the code this is always a good rule to follow.