How I Understand Hoisting in JS

Katrina Tochowicz
The Startup
Published in
2 min readSep 3, 2020
Matryoshka dolls

Take a look at the code below:

function bigDoll() {  function littleDoll() {
return 'i am little'
}
return littleDoll() function littleDoll() {
return 'no I am little!'
}
}bigDoll()

What do you think will be the return value?

This took me some time to understand, so I’ll try my best to explain what’s going on here.

First, we can say that the function bigDoll() is written in the global execution context which is also viewed as the first stack in the call stack.
Both littleDoll() functions are written inside of bigDoll() so we can say that the littleDoll() functions are written in the function execution context. When the JS engine runs the bigDoll(), it sees a return value of littleDoll(). But at this point, we don’t know what littleDoll() is.

Let’s visualize this:

function bigDoll() {  function littleDoll() {
return 'i am little'
}
littleDoll() function littleDoll() {
return 'no I am little!'
}
}bigDoll()

Okay, so what is the value of littleDoll() ? Well, inside of first littleDoll() the function’s return value is ‘i am little’. Ok great.
But hang on.
We’re still not done executing bigDoll().
There’s a second littleDoll() and now, this tells the JS engine to REWRITE the value in littleDoll() that’s stored in memory to equal this new value: ‘no I am little!’. Which is why…

…the return value of bigDoll() is…

‘no I am little!’

Hope you got that right and I hope I explained this well. If not, let me know! I’d be happy to make revisions!

Code example courtesy of ZeroToMastery.

❤ Happy coding ❤

--

--