Hoisting
Today’s TIL is on hoisting. It’s one of those concepts I’ve been knowing ‘vaguely’ but not specifically enough.
Hoisting is when function, variable, and class declarations are pulled up to the top of the scope prior to code execution.
Honestly , this prior to code execution part really stumped me, because I learned that JavaScript is an interpreter language, which means it doesn’t have a separate compilation phase and executes the code at run-time. But hoisting implies that JavaScript must have gone through the code and pulled these declaration to the top prior to run-time execution. Long story short, my takeaway on this topic is that while JavaScript is an interpreter language, it has a creation and execution phase. And it is during the creation phase that hoisting takes place. :-)
Due to hoisting, a variable declared with the var
keyword does not throw a Reference error
:
console.log(foo); // undefined
var foo = 'bar';
console.log(foo); // "bar"
Important note 1:
Hoisting only pulls up the variable declaration. Variable assignment is not hoisted and is executed at run-time.
This is why, even though the var foo = 'bar'
statement has both a declaration and assignment phase, the first console.log stated undefined
. When a variable is declared, JavaScript initializes its value to undefined
.
One catch with let
and const
:
Variables declared with let
and const
are also hoisted (I didn’t know this) BUT they are not initialized (initial value is not assigned).
Therefore, even though those variables are hoisted, accessing them before value assignment will cause a ReferenceError
.
Important note 2:
Function hoisting only takes place with function declarations.
hello(); // "hello"
function hello() {
console.log('hello');
}
Function expressions are not hoisted because they are essentially the same as variable assignments. If you try to call a function prior to its function expression, you will get a Cannot access 'hello' before initialization
error. Note, this is a different error compared to when you call a function that never been declared (Uncaught ReferenceError: hello is not defined
).
References: What is Hoisting in JavaScript? MDN’s Hoisting