What is Hoisting in JavaScript
By FoxLearn 2/14/2025 8:54:52 AM 35
This means that you can refer to variables and functions even before they are actually written in the code. However, only the declarations are hoisted, not the assignments or initializations.
1. Only Declarations Are Hoisted, Not Initializations
You might encounter errors when trying to use a variable that doesn’t exist yet in your code:
// Throws ReferenceError: testing is not defined HoistingExample(); function HoistingExample() { console.log(testing); console.log("Hello World!"); }
So, why doesn’t this happen with the following code?
HoistingExample(); function HoistingExample() { // Logs undefined, not an error console.log(variable1); var variable1 = "something"; };
This is because hoisting only applies to variable declarations, not initializations. JavaScript moves the declaration (var variable1;
) to the top, but leaves the initialization (variable1 = "something";
) where it is. Here’s how the interpreter processes the code:
HoistingExample(); function HoistingExample() { // The variable is hoisted to the top var variable1; // So, it's undefined, not throwing an error console.log(variable1); // Then, it's initialized with a value variable1 = "something"; };
2. let
and const
Are Hoisted, But Not Initialized
What happens if we use let
or const
instead of var
? The behavior changes.
// Throws ReferenceError: Cannot access 'variable1' before initialization HoistingExample(); function HoistingExample() { console.log(variable1); let variable1 = "something"; };
While let
and const
are hoisted, they are not initialized until their actual declaration in the code. This causes a ReferenceError. To avoid this, just make sure to initialize the variable before accessing it.
3. Hoisting Doesn’t Apply to Function Expressions
You might think that hoisting works the same way for function expressions, but it doesn’t.
// Throws Uncaught TypeError: HoistingExample is not a function HoistingExample(); var HoistingExample = function() { console.log("Hello World!"); };
In this case, JavaScript tries to hoist the function declaration, but since it's stored in a variable, it doesn’t behave the same way. The variable itself gets hoisted, but it’s undefined
at the time of the function call, leading to an error.
- How to convert voice to text in Javascript
- LET vs VAR in JavaScript Variable Declarations
- How to add voice commands to webpage in Javascript
- How to capture an image in javascript
- How to Build Your Own JavaScript Library
- How to reverse a string properly in Javascript
- How to bypass 'Access-Control-Allow-Origin' error with XMLHttpRequest
- How to get the client IP address in Javascript