JS Hoisting

Skabe89
2 min readOct 14, 2021

When we look at code we generally read it from top down. If we want to declare a variable, and have a function work off this variable we would do our declarations on the top of the page like so.

let greet = "Hello"function greetBob(){
return greet + ', Bob.'
}
console.log(greetBob())

Our console will log out “Hello, Bob.” just as we expected it to. What happens when we move up our console log/invocation of the greetBob function so that it comes before we define the function?

let greet = "Hello"console.log(greetBob())function greetBob(){
return greet + ', Bob.'
}

The console will still log out “Hello, Bob.” just like we want! The function greetBob is hoisted and treated as if it were declared before the position it falls on our page.

JavaScript Hoisting refers to the process whereby the interpreter allocates memory for variable and function declarations prior to execution of the code. Declarations that are made using var are initialized with a default value of undefined. Declarations made using let and const are not initialized as part of hoisting.Conceptually hoisting is often presented as the interpreter "splitting variable declaration and initialization, and moving (just) the declarations to the top of the code"-MDN web Docs (https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)

Note that the declarations are hoisted, whereas function expressions are not

let greet = "Hello"console.log(greetBob())var greetBob = function(){
return greet + ', Bob.'
}

This will result in an error that reads ‘greetBob is not a function’. This is because the interpreter is recognizing that the variable greetBob exists, but at the moment it is invoked in our console.log it is undefined.

Let’s look at an example of hoisted variables. So if we had code that looked like this

console.log(frog) //undefined
console.log(cat) //undefined
var frog = 'Frog'
var cat = 'Cat'
console.log(frog) //'Frog'
console.log(cat) //'Cat'

the interpreter would see it more like

var frog
var cat
console.log(frog) //undefined
console.log(cat) //undefined
frog = 'frog'
cat = 'cat'
console.log(frog) //'Frog'
console.log(cat) //'Cat'

The variable declarations, not the initializations are hoisted.

It can get messy. I’ve always been taught to avoid relying on hoisting variables and functions when writing code. I try to treat the order in which I declare and initialize with care and do things in order to avoid confusion.

--

--