Two weeks ago I gave a lightning talk at Caphyon on hoisting in JavaScript. Putting aside all the common jokes about the JS language, people really seemed to like it. It was kind of a challenge to talk about JS while having an audience of C++ and Java colleagues.
Now getting back to the talk, that was lightning ⚡️ fast and it didn’t covered that much as I would’ve liked to. So I’ll try to write a bit more on JavaScript scoping and hoisting bellow.
Hosting Hoisting
On the clickbait talk title, that’s actually a true story. Last time I mentioned the hoisting term into an article of mine, I remember that a friend read it and told me I had a typo in the article.
So what’s hoisting in JavaScript? The short answer is that, conceptually, variable and function declarations are moved/hoisted to the top of their scope before code execution.
Variable declaration
When declaring a variable, only its name gets hoisted.
Here’s how the above is interpreted, thus undefined
.
Function declaration
Unlike var, a function declaration hoists its actual definition too.
Here’s how the above is interpreted, thus “Hello world”
:
Function expressions
The variable name gets hoisted, but not the function assignment.
Here’s how the above is interpreted, thus hello is not a function
:
On ES6 and later
The hoisting behavior isn’t something that applies to latest ECMAScript gems:
- let
- const
- class declaration
- arrow function
Last but not least
Here’s what Brendan Eich said about JS hoisting:
var
hoisting was an implementation artifact. source
function
hoisting was better motivated: function declaration hoisting is for mutual recursion & generally to avoid painful bottom-up ML-like order source
The slides
Here are the slides, just in case.