JavaScript Hoisting

Paige Miles
2 min readMay 2, 2021

When you execute javascript code, the JavaScript engine creates the global execution context, which has two phases: creation and execution.

During the creation phase, the JS engine moves the variable and function declarations to the top of your code. This process is known as hoisting.

Variable hoisting

The var keyword

console.log(greeting);var greeting = “Hello World!”

This code won’t cause an error and will result in the printing of “Hello World!” because the JavaScript engine hoists the variable declaration to the top of the script:

var greeting = “Hello World!”console.log(greeting)

During the creation phase, the JavaScript engine places the greeting variable in memory and initializes the value to undefined, so the code looks like this in the execution phase:

var greetingconsole.log(greeting) // undefined
greeting = “Hello World!”

The let keyword

console.log(greeting)let greeting = “Hello World!”

The javascript engine hoists variable declarations that use the let keyword but does not initialize those variables; therefore, the above code will throw an error.

Function hoisting

The javascript engine hoists function declarations to the top of the script during the creation phase.

let x = 30, y = 10;let result = subtract(x, y)
console.log(result)
function subtract(a, b){
return a — b
}

The function is hoisted. The above code is the same as:

function subtract(a, b){
return a — b
}
let x = 30, y = 10;let result = subtract(x, y)
console.log(result)

Function expressions

The above code is written as a function expression:

let x = 30, y = 10;let result = subtract(x, y)
console.log(result)
var subtract = function(a, b){
return a — b
}

If you recall, the var keyword means that during the creation phase, the variable “subtract” is added to memory, and its value is initialized to undefined. It is not a function, so the above code will result in an error when executed.

Arrow functions

The same code is written as an arrow function:

let x = 30, y = 10;let result = subtract(x, y)
console.log(result)
var subtract = (a, b) => a — b

Execution of this code will also yield an error as arrow functions aren't hoisted in the same way as function expressions.

--

--

Paige Miles

Full-stack developer. Funny-peculiar. Lover of baking, yoga, and reading (between the lines).