RIPPLE : RUBEK MAHARJAN
In JavaScript, hoisting is a behavior where variable and function declarations are moved to the top of their scope before the code is executed. Understanding hoisting is important because it can affect how your code works and help you avoid errors.
How Hoisting Works:
1. Hoisting with Variables:
var
Declarations: When you declare a variable withvar
, JavaScript hoists the declaration to the top of its scope. However, the assignment stays where it is. This means the variable isundefined
before it is assigned a value.
console.log(myVar); // undefined
var myVar = 10;
console.log(myVar); // 10
let
andconst
Declarations: These variables are also hoisted, but they cannot be accessed before they are initialised. If you try to use them before they are assigned a value, you’ll get an error.
console.log(myVar); // ReferenceError
let myVar = 10;
2. Hoisting with Functions:
- Function Declarations: The entire function (including its body) is hoisted, meaning you can call it before it appears in the code.
greet(); // "Hello!"
function greet() {
console.log("Hello!");
}
- Function Expressions: If you assign a function to a variable, only the declaration is hoisted, not the function definition. Calling the function before it is assigned results in an error.
myFunc(); // TypeError
var myFunc = function() {
console.log("Hello!");
};
Why Hoisting Matters:
- Avoid Confusion: Hoisting can lead to unexpected results if you don’t understand it. For example, using a
var
-declared variable before its value is assigned can result inundefined
.
2. Best Practices:
- Declare variables at the top of their scope.
- Use
let
andconst
to avoid issues with hoisting. - Be cautious with function expressions and avoid calling them before they are defined.
Real-Life Example:
Imagine you try to use a variable before declaring it:
showStatus();
function showStatus() {
console.log(status); // undefined, not ReferenceError
var status = "Active";
}
Here, hoisting moves the variable declaration to the top, but the value is still undefined
until the code assigns it.
Conclusion:
Hoisting moves variable and function declarations to the top of their scope, but the behaviour differs depending on whether you use var
, let
, or const
. By understanding hoisting, you can avoid bugs and write more predictable JavaScript code. Always declare your variables at the top and be careful when using functions and variables before they are initialised.nt process. Learning front-end development can be both rewarding and overwhelming. However, with consistent practice, you can master it.