Basics
JS Hoisting
JavaScript Hoisting Explained
JavaScript hoisting moves declarations, differing for var vs. let/const.
What is Hoisting?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase. This allows functions to be called and variables to be referenced before they are declared in the code.
Hoisting with <code>var</code>
In JavaScript, var
declarations are hoisted to the top of their function or global scope. However, only the declaration is hoisted, not the initialization. This can lead to unexpected behavior if not understood properly.
In the example above, console.log(x)
before var x = 5;
logs undefined
because the declaration is hoisted, but the assignment occurs later.
Hoisting with <code>let</code> and <code>const</code>
Unlike var
, let
and const
are hoisted but are not initialized. This results in a Temporal Dead Zone (TDZ) where accessing the variable before its declaration results in a ReferenceError.
As shown in the examples, accessing let
or const
variables before declaration results in an error, unlike var
which returns undefined
.
Function Hoisting
Function declarations are fully hoisted, meaning both the function's name and the function's body are moved to the top of the scope. This allows you to call a function before it is declared in the code.
The above example demonstrates that the function greet
can be called before it is declared, due to hoisting.
Conclusion
Understanding hoisting is crucial for debugging and writing predictable JavaScript code. Remember that var
declarations are hoisted and initialized with undefined
, while let
and const
are hoisted but not initialized, leading to potential errors if accessed prematurely.
Basics
- Introduction
- Where To
- Output
- Syntax
- Comments
- Variables
- Scope
- Hoisting
- Errors
- Data Types
- Operators
- Ternary Operator
- Short-Circuit Evaluation
- If Else
- Switch
- Loops
- For...Of/For...In
- Functions
- this Keyword
- Objects
- Arrays
- Strings
- Template Literals
- Numbers
- Number Properties
- Dates
- Math
- Booleans
- Type Conversion
- Destructuring
- Spread/Rest
- RegExp
- Strict Mode
- Modules
- Security Basics
- Debugging
- Best Practices
- Mistakes
- Performance
- Reserved Words
- Sets
- Maps
- Bitwise
- Array Const