What is hoisting in Javascript?
charliekroon
Posted on April 6, 2023
In the upcoming three weeks, I’ll publish a small blog series called “Questions from the past”. I’ll be going through my old notebooks from my first year as a developer and answer the questions I think are most important. For this first blog in the series, let’s discuss the concept of hoisting in Javascript.
Despite its name, hoisting in Javascript has nothing to do with lifting something up or moving something around. All it means is that JS sets up memory space for variables and functions that you create in your code. This way, when your code starts running and gets executed line by line, JS can access these variables and functions.
However, when Javascript sets aside that memory space, it doesn’t know what the value of the variables and functions will be. Therefore, it sets a placeholder called undefined.
What’s interesting about hoisting is that the Javascript engine may execute your code in a different order than the way it’s written. That’s because it can access variables and functions that were hoisted before they were even declared in the code. But since the value of hoisted variables and functions is undefined, relying too heavily on hoisting can lead to unexpected results.
Let’s take a look at this code:
console.log(a)
console.log(b)
var a = "I am a variable!"
function b() {
console.log("I am a function!")
}
In most programming languages, you might expect an error as soon as you try to run this code, but with Javascript, it’s different. Because the memory space is already set aside for the variable and the function before the code is executed, it will not throw an error. What it will do is return undefined. So, while you can technically call functions and variables that are declared later, it’s generally not a good idea to rely too much on hoisting.
So, in summary:
Hoisting in Javascript simply means JS sets up memory space for variables and functions that you create in your code. This way, when your code starts running and gets executed line by line, JS can access these variables and functions.
Variables and function declarations can be hoisted.
It’s best to declare variables and functions before accessing them. This way you’ll avoid weird bugs and undefined warnings in your console.
Posted on April 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.