Understanding Hoisting in JavaScript: var, let, const, and Functions
JavaScript hoisting is one of those concepts that looks simple at first but can cause confusing bugs when declarations appear to work before they are written. Understanding what the JavaScript engine does during the creation phase makes these behaviors much easier to predict. Hoisting affects variables, functions, and different declaration types in different ways. In this guide, we will break…
JavaScript hoisting can be a tricky concept to grasp. It involves the JavaScript engine preparing the execution environment and registering declarations before the code is executed line by line. This is why a function declaration can be called even before its position in the source code.
For example, function greet() can be called right away, even though it appears below its declaration in the code. This is because function declarations are fully initialized during the creation phase, allowing them to be called before they appear in the code.
On the other hand, var variables exist before assignment but initially contain undefined value. This means that if you try to log a var variable before its declaration, it will display undefined.
In contrast, let and const declarations remain inaccessible in the beginning of the scope until execution reaches their declaration. This period is known as the Temporal Dead Zone or TDZ. If you attempt to access a let or const variable before its declaration, it will throw a ReferenceError.
Function expressions are different from function declarations. They follow the same variable declaration rules as let and const, meaning they cannot be used before initialization without causing an undefined or ReferenceError.
To better understand hoisting, it's essential to stop thinking of JavaScript physically moving declarations to the top of the file. Instead, consider the engine creating bindings before executing statements, with different declaration types receiving different initialization behavior.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.