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!
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!!
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 initialization
let a = 'Remy'
const b = 'Linguine'
console.log(a) // 'Remy'
console.log(b) // 'Linguine'
So it seems these variables _are _being hoisted somewhere! Otherwise we would’ve received an error that they didn’t exist, i.e. “not defined”. We know that let
and const
are only evaluated during the time of execution, so they aren’t initialized with an undefined
value like variables with var
do.
So if the let and const variables are being hoisted, but not given any value, where do they go? What weird sort of purgatory exists where uninitialized let
and const
variables wait to be evaluated? What bizarre, seedy JavaScript underbelly are these poor variables trapped in, shouting out helplessly to their merciless overlords (the Compiler and the Runtime) to let them bask in the sunlight of initialization??
#javascript #nodejs #software-engineering #technology #programming