All 28 lessons ▾
Inside JavaScript · Lesson 3 of 28
Hoisting: Why You Can Use Things Before You Write Them
Can you call a function before you've written it? Can you read a variable before it has a value? In most languages, no. In JavaScript... yes! So let's see why.
Got a doubt? Ask in the comments under the video.Subscribe
- Hoisting: use variables and functions before you write them
- It comes from phase one, the memory creation phase
- var gets undefined; a function declaration gets its whole body
- Not in memory at all: ReferenceError, not defined
- Arrow functions and expressions act like variables: TypeError
- Hoisting is not code moving to the top
Part 1A little magic
Let me show you some magic today. Something that would crash in most programming languages, but works perfectly fine in JavaScript.
1var score = 50;2 3function sayHi() {4 console.log("Hi there!");5}6 7sayHi();8console.log(score);Hi there! 50
First, a normal program. A variable score, which is fifty. And a function sayHi, that just says hi there. Then at the bottom, we call sayHi, and log the score. What do you expect? Easy. Line seven prints hi there. And line eight prints fifty. No surprises at all.
Part 2Now, the magic
I'll take those two calls, and move them to the very top. Before the variable even exists. Before the function is even written.
What do you expect now? Think about it for a second. We're calling sayHi before it's written, and reading score before it has any value. In most programming languages, this is a straight error. You can't use something that doesn't exist yet. But JavaScript? It runs! sayHi says hi there, perfectly. And score gives us something weird. Not an error. Not fifty. Undefined.
This magic has a name. It's called hoisting. Hoisting is how JavaScript lets you use variables and functions even before you've written them, without any error. Let me put it in one line. With hoisting, you can access things before you declare them. But why does this happen? Is JavaScript secretly moving your code to the top? No! Let's see what's really going on behind the scenes.
Part 3Why it works
Remember the last episode? Before running a single line, JavaScript does phase one, the memory creation phase. And the whole answer is hiding right there.
1sayHi();2console.log(score);3 4var score = 50;5 6function sayHi() {7 console.log("Hi there!");8}Hi there! undefined
Here's our magic program. The global execution context is created, and pushed onto the call stack. Now phase one. JavaScript scans the program from top to bottom. score gets a reserved seat, with the placeholder undefined in it. And sayHi? It's a proper function, so the whole function is stored, exactly as you wrote it. Memory is ready, and not a single line has run yet.
Now phase two. Line one calls sayHi. Is sayHi in memory? Yes! It's already there, the whole function. So it simply runs. A new execution context goes on the stack, and the arrow jumps to line seven, which prints hi there. Job done, so it's popped. Line two. console.log score. JavaScript looks in memory and finds score, but its value is still the placeholder. So we see undefined. No error! Line four, and only now, score finally becomes fifty. And when the program ends, the call stack is empty again.
So remember this. In phase one, a var gets undefined. And a function declaration gets the whole function. Both of these happen before your first line even runs. That's why you could call sayHi early. And that's why score was undefined, not fifty. That's hoisting.
1startApp();2 3function startApp() {4 loadUser();5 showHome();6}7 8function loadUser() { /* ... */ }9function showHome() { /* ... */ }And this isn't just a trick for interviews. It's actually useful. Because function declarations are hoisted, you can write your main logic at the top of a file, and keep the small helper functions at the bottom. Look at this. startApp runs first, and it calls loadUser and showHome, which are written further down. It works, because all three were stored in memory during phase one. Your file reads like a story, top to bottom. Nice.
Now, here's why this matters in real code. Say you use a var before its line, and do some math with it. Like price times two. You won't get an error. You'll get NaN, not a number, because undefined times two is not a number. So instead of a crash that tells you where the problem is, you get a silent wrong answer. Bugs like this are hard to find, unless you understand hoisting. And now you do!
Part 4undefined vs not defined
Now let's play with it a little more. What if I delete the line var score equals fifty completely?
1sayHi();2console.log(score);3 4function sayHi() {5 console.log("Hi there!");6}Hi there! ReferenceError: score is not defined
Now in phase one, memory has only sayHi. There's no score anywhere. Not even a reserved seat. Line one, and sayHi still says hi there. Line two, console.log score. JavaScript looks in memory, and score isn't there at all. So this time, we get an error. A reference error. score is not defined. And the program stops right here.
So, are undefined and not defined the same thing? No! Remember this. Undefined means the variable is in memory. It has a reserved seat, but no real value yet. Not defined means it isn't in memory at all. There's no seat for it. Two completely different things. And we'll go even deeper into this in a later episode.
Part 5Functions that act like variables
One more interesting thing. Not every function is hoisted the same way. Watch this.
1sayHi();2 3var sayHi = () => {4 console.log("Hi there!");5};TypeError: sayHi is not a function
This time, sayHi is an arrow function, stored in a variable. In phase one, JavaScript sees var sayHi, so it treats it like any other variable. It gets undefined. Not the function, just undefined. Now line one tries to call sayHi. But sayHi is undefined right now, and you can't call undefined. So we get a type error. JavaScript complains, sayHi is not a function!
1sayHi();2 3var sayHi = function () {4 console.log("Hi there!");5};And the same thing happens with a function expression, like this one. Again, it's a var. So in phase one it gets undefined, and calling it early throws the same type error. Only a proper function declaration, starting with the word function, gets the whole function copied in phase one.
So remember this rule. Only function declarations are hoisted with their whole body. Arrow functions and function expressions behave just like variables. In phase one, they get undefined.
Part 6The interview answer
Now, this is a very common interview question. And most people answer it wrong.
1console.log(city);2var city = "Pune";3 4console.log(country);What does line one print?
Show the answer
City is a var, so in phase one it got undefined. So line one prints undefined. And line four? There's no country anywhere in the program. It's not in memory at all. So that's a reference error, country is not defined. Did you get both right? Then you've understood hoisting!
Before this video, what did you think hoisting was?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.