?? Demystifying Hoisting in JavaScript! ??
Amit Sheoran
Software Engineer Javascript | | ReactJs | | Redux | | React-native | | web3
?? What is hoisting, you ask? Most of us know it involves the declaration of functions and variables moving to the top of their scopes. But what's the real scoop behind the curtain? Let's dig in! ???♂?
?? Definition: Hoisting is a JavaScript behavior where declarations of functions, variables, or classes are moved to the top of their respective scopes during the compilation phase, before code execution.
?? Behind the Scenes: The Unveiling! Yes, we've all heard about hoisting, but have you delved into its intricate dance with functions and variables?
1?? Function Declarations: During compilation, functions are allocated memory, allowing them to be invoked even before they appear in the code. Watch the magic unfold:
hoistedFunction(); // Works like magic!
function hoistedFunction() {
console.log("Function hoisting at play!");
}
2?? Variable Declarations: var variables are hoisted but initialized with undefined. Beware of the intricacies:
console.log(myVar); // Outputs: undefined
var myVar = 42;
console.log(myVar); // Outputs: 42
3?? Function Expressions: Brace yourself for the unique ballet of function expressions. The variable is hoisted, but the assignment is held back until encountered:
console.log(myFunc); // Outputs: undefined
var myFunc = function() {
console.log("I am a function expression!");
};
myFunc(); // Outputs: I am a function expression!
?? Understanding the Art: Craft Predictable Code! Unravelling the magic behind hoisting empowers you to craft cleaner, more predictable code. Embrace the nuances, leverage the magic, and elevate your JavaScript artist??
?? Question for You: What's your favourite JavaScript hoisting quirk, and how do you leverage it in your code? Share your insights in the comments! ????