The Truth About Hoisting in JS
Entering the Temporal Dead Zone
Earlier this week I was preparing to give a tech talk about some foundational JavaScript concepts to know for tech interviews. As always, when prepping content to share, I was obsessively going over the details to make sure all of my facts were correct. I would never want to steer anyone wrong. After all, these articles and talks are made to help people, not hinder them!
var, let, and const
As I was reviewing the slides for the difference between var
, let
and const
, I found myself questioning the statement that var
is the only one hoisted. This ‘fact’ was told to me by an interviewer awhile back, and I figured he must be right due to his extremely reputable title and company.
I knew that yes, var
is definitely hoisted and initialized with an undefined
value. I also learned that if you have an undeclared variable inside of a function, it will automatically be hoisted to the top of the scope during the compilation phase, and initialized as a global variable with an imaginary var
like so:
In this example, when exterminator()
is called, the now global variable of cockroachA
(which was initialized with undefined
) is initialized with its new value “I’m alive!”. cockroachA
has escaped the exterminator. He lives!!
But what about let and const?
As I was testing out code examples, I realized that when I referenced a variable above where they were declared, the variables with let
and const
weren’t throwing a reference error saying “not defined”. Instead the reference error said “Cannot access ‘a’ before initialization”. Hmm. 🤔
console.log(a)
// ReferenceError: Cannot access 'a' before initialization
console.log(b)
// ReferenceError: Cannot access 'b' before initializationlet a = 'Remy'
const b = 'Linguine'console.log(a) // 'Remy'…