Why Hoisting: Javascript.

Ignatius Sani
CodeX
Published in
6 min readOct 8, 2021

No! there isn’t lifting up, but a memory.

For some time now, I’ve been making research about what hoisting is and, after some research, I discovered that not all the resources about this particular concept are 100% clear. So that’s why I’ve taken the time to write this article in a way that it's simple enough to grasp.

Everyone is welcome to read this article but of course, you should have a strong knowledge of the basics of Javascript. Alright, we can finally dive in and learn what hoisting is all about.

The big question: What is hoisting?

Photo by Evan Dennis Unsplash

Hoisting is a phenomenon in javascript where a function or variable can be accessed or called even before they initialized.

Let’s examine this code sample so this is more intuitive:

getCoffee();console.log(x)console.log(y)
var x = 'something....'
function getCoffee(){
console.log('get me some coffee');
}

we noticed that “getCoffee” function gets called even before it was created, hmm, we should expect an error you might think, but there’s something really strange going on here if we copy the following code into our developer tool, we will realize there are a couple of things going on.

We get this result when we run the code in the browser, I want you to focus on three things here are the first result which is gotten from the function “getCoffee()”, the undefined, which is gotten from console logging x, and lastly an Uncaught ReferenceError: saying y is not defined gotten from console logging y.

Let’s pretend we at least understood the “getCoffee()” function, how about the undefined returned from console logging x, why don’t we also get the result and print it out? well I will answer that question but first I want you to know this is caused by hoisting in javascript, hoisting can exist in two forms namely: Partially hoisted and fully hoisted.

What’s their difference anyway? Partially hoisted set the value of its variable to undefined, during the creation phase. We can see this clearly when we check the window object. You should already see variable x set to undefined in the screenshot below. It got allocated memory, but it's not assigned a value so it automatically set this value to undefined. Note, that this happens in variables(var) but is not applicable to the ES6 variables i.e let and const.

In fully hoisted, functions get allocated memory as well but have its value defined, we return the full function. When checking the window object also we will find out the function “getCoffee” is present and it returns the full function just as it was written in our code editor. Take some moment with the screenshot below, to get more clarity on what's happening in the background.

Less, I forget, you remembered the console.log(y) that threw the ReferenceError: y is not defined? we get this error because there’s no variable called y in our code, so we get a referenceError, it is important to note that “not defined” is different from “undefined”. Yes, they are different, “not defined” as we can clearly see implies that variable y is not present or doesn’t exist simply like that, while undefined simply means that variable is present but its value is not set.

Oh boy! that’s too much to take in, go take a little break, and you can continue... Welcome back! so what’s really happening behind the scene?

Behind the scenes

There is a lot going on in the background when hoisting takes place, variables and functions get allocated memory during the creation phase, for variables they receive a special value of undefined while functions are defined. the javascript engine looks out for two particular keywords if hoisting must happen, they are the var and the function declaration. If these keywords are not present we get a referenceError.

(function cook(){ 
console.log('cooking....')
})
// if we try to call the cook() function we will get Uncaught ReferenceError: cook is not defined

We are wrapping the function declaration with a bracket, we are doing this to hide the function from hoisting. Because the Javascript engine doesn’t find the function keyword, it throws an error.

Does hoisting happen in all functions?

well, No it doesn’t happen, the reason is this, amongst the three different ways of calling function, these different ways which are function expressions, function declaration, and the arrow function, only function declaration gets hoisted.

// function expressionconsole.log(playSong())var playSong = function(){ console.log('playing jason derulo')}If we try to call the function we will get an error, this is because we can only call the playSong() function after its defined

They both get partially hoisted, which means they get undefined as a value. But the tricky part though is we can only get this behavior if we console.log(playSong) and not calling the function

console.log(playSong)var playSong = function(){ console.log('playing jason derulo')}
this way we can get the exact behavior as the var variable.

Lastly, for the arrow function, we get this same behavior as the function expression. So there’s no need to go over that again.

Is hoisting a good practice?

Let’s take a look at this code snippet

read()function read(){
console.log('I am reading some novel')
}
function read(){
console.log('I am done reading the novel')
}
function read(){
console.log('I am confused')
}

Which function gets returned? Well, during the execution phase in javascript, the javascript engine reads the code from beneath to the top, and allocate memory to the written code, if we have the same function as above it will only allocate memory to the last one no matter how many times it found that same function. The big problem here is other functions aside from the last one will always get overwritten, which means we won’t be able to run other functions. One of the best practices when it comes to writing good programs is predictability, when you use hoisting, you will never be able to predict your code. In my own opinion, you shouldn’t write programs that are not predictable. So I will say avoid hoisting.

To summarize

Wow, finally we are done.

Let’s try to review everything we’ve learned so far, during hoisting memory is allocated to a function or a variable, they get assigned a value, hoisting can exist in two forms fully and partial, all variables declared in var are partially hoisted while functions declaration are fully hoisted. The javascript engine looks out for two keywords: function and var, lastly, you should try to avoid hoisting because it overwrites your code and makes predictability difficult in your program. That’s it, guys. As always feel free to send your feedback and things you think I could improve on. Cheers and happy coding.

Inspiration derived from Javascript: the advance concept by Andrei Neagoie founder of zero to mastery.

--

--

Ignatius Sani
CodeX
Writer for

I'm a Ruby on Rails full-stack developer specializing in mobile and frontend development.