?? The Ultimate Guide to Hoisting in JavaScript
Hanan Fadel
Senior Software Engineer @Scotiabank | Java, Spring Boot, REST API, React, Angular, JavaScript
Understanding hoisting in JavaScript is essential for writing bug-free, predictable code. Let’s demystify hoisting, explore its nuances, and compare traditional vs. modern approaches to variable and function declarations.
?? What is Hoisting?
Hoisting is JavaScript’s default behavior of moving declarations to the top of their scope during the compilation phase. This means variables and functions can be referenced before they are declared in the code.
?? Traditional vs. Modern Examples
Example 1: Variable Hoisting
Traditional Approach (var):
console.log(myVar); // Output: undefined
var myVar = 10;
Explanation: The declaration var myVar is hoisted to the top, but the initialization myVar = 10 remains in place. Hence, undefined is logged.
Modern Approach (let/const):
console.log(myVar); // ReferenceError: Cannot access 'myVar' before initialization
let myVar = 10;
Explanation: let and const declarations are hoisted but remain in a "temporal dead zone" (TDZ) until their initialization is encountered.
Example 2: Function Hoisting
Traditional Approach (Function Declaration):
sayHello(); // Output: Hello, World!
function sayHello() {
console.log("Hello, World!");
}
Explanation: Entire function declarations are hoisted, allowing them to be called before they appear in the code.
Modern Approach (Function Expressions):
sayHello(); // TypeError: sayHello is not a function
const sayHello = function () {
console.log("Hello, World!");
};
Explanation: Only the declaration of sayHello is hoisted, not its initialization. Hence, it behaves like a variable in the TDZ.
领英推荐
?? Key Use Cases and Insights
1?? Variables in Global Scope:
console.log(x); // undefined
var x = 5;
console.log(x); // 5
2?? Function Expressions vs. Declarations:
hoisted(); // Works because it's a function declaration
function hoisted() {
console.log("I am hoisted!");
}
notHoisted(); // Error: notHoisted is not a function
const notHoisted = function () {
console.log("I am not hoisted!");
};
Takeaway: Use function expressions when you want tighter control over execution.
3?? Class Hoisting:
const obj = new MyClass(); // ReferenceError: Cannot access 'MyClass' before initialization
class MyClass {
constructor() {
console.log("I am a class!");
}
}
Takeaway: Classes behave like let and const declarations and are subject to the TDZ.
?? Best Practices to Avoid Hoisting Pitfalls
?? Key Takeaways
By understanding and embracing these principles, you can write more predictable and robust JavaScript code. How has hoisting impacted your projects? Share your experiences and tips in the comments below! Let’s discuss and grow together. ??
#JavaScript CrackInterview Hanan Fadel #CleanCode #WebDevelopment #ProgrammingTips
COO at Viso | Strategic Partnerships | Accelerating B2B Success with Tailored Tech Solutions.
1 个月Nice one, Hanan!