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

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!”
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)

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.

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.

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store