Hoisting for dummies (aka me)
Bibi
Posted on June 5, 2024
TL/DR:
Hoisting is a useful JavaScript feature that allows you to use variables and functions before they are declared. However, it's crucial to remember that only declarations are hoisted, not assignments. The keywords let
and const
have different hoisting behaviours, and strict mode can be used to avoid potential hoisting-related issues.
A quick guide to hoisting 🏗️
Hoisting is one of those buzzwords you hear about only two times in your dev life, one is during that pesky interview and the other is when you're in school. But guess what? I never learned it (or maybe I did and forgot, sorry teacher). So, let's find out what the mystery of ✨hoisting✨ is.
The textbook definition of hoisting is to lift something heavy, to move from a lower position to a higher position.
Interesting... But still doesn't click for me.
MDN defines hoisting as:
the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, prior to execution of the code.
Ah. Now I get it.
This means that regardless of the their actual placement within the scope, you can use them as if they were declared at the beginning. If you're familiar with the black magic of var
, that is basically hoisting at it's finest. Just add functions, classes and imports into the mix.
There is a few catches though. Only declarations are hoisted, not assignments. It also doesn't apply to arrow functions, as they are declared with the const
keyword.
I'm a visual person, so I made some ~cool~ graphics using Figma. Check this out:
Alright, I think that's it for me ┗(・ω・;)┛
Here are some key points to take home:
- Variable and function declarations are hoisted: Hoisting applies only to declarations, not assignments. For instance, the declaration ‘var headcount’ is hoisted, but the value assignment ‘var headcount = 10’ remains at its original location.
-
let
andconst
behave differently: Unlikevar
, which is hoisted to the top of its scope,let
andconst
variables are declared in the place they are written. Attempting to access a let or const variable before its declaration will result in a reference error. -
Hoisting in Strict Mode: JavaScript offers a "strict mode" to prevent potential issues caused by hoisting. When running code in strict mode,
let
andconst
variables are no longer hoisted, ensuring clear and error-free code.
Hope you learned something with me today! (´◡`)
Bibi
Posted on June 5, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 31, 2022