Hoisting is a behavior in JavaScript variable and function declarations are moved to the top of their respective scopes (global or local) before the code is executed. This means that even if a variable or function is declared later in the code, it can be used before its actual declaration.
There are a few important concepts to understand to master hoisting in JavaScript:
1. Variable Hoisting: In JavaScript, variable declarations are moved to the top of their scope during hoisting, but their assignments are not. This means that if you declare a variable using "๐ฏ๐๐ซ", it will exist in memory with a default value of "๐ฎ๐ง๐๐๐๐ข๐ง๐๐" before its actual declaration in the code.
// For example:
console.log(myVar); // Output: undefined
var myVar = 5;
This code will log "undefined" to the console, because "myVar" exists in memory with a default value of "undefined" before its declaration on the second line.
2. Function Hoisting: Function declarations are also hoisted in JavaScript, meaning they can be used before their actual declaration in the code. This is because function declarations are moved to the top of their scope during hoisting, including their entire code block.
// For example:
myFunc(); // ๐๐ฎ๐ญ๐ฉ๐ฎ๐ญ: "Hello World!"
function myFunc() {
console.log("Hello World!");
}
This code will log "๐๐๐ฅ๐ฅ๐จ ๐๐จ๐ซ๐ฅ๐!" to the console, even though "๐ฆ๐ฒ๐ ๐ฎ๐ง๐" is called before its actual declaration in the code.
3. Block Scoping: In modern JavaScript, "let" and "const" keywords are used for block-scoped variable declaration. Unlike "var", block-scoped variables are not hoisted to the top of their scope, and cannot be accessed before their actual declaration in the code.
// For example:
console.log(myVar); // Output: ReferenceError: myVar is not defined
let myVar = 5;
This code will throw a ๐๐๐๐๐ซ๐๐ง๐๐๐๐ซ๐ซ๐จ๐ซ, because "myVar" is not hoisted and cannot be accessed before its actual declaration on the second line.
In summary, hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their respective scopes during the code execution. Understanding variable hoisting, function hoisting and block scoping hoisting is important for mastering hoisting in JavaScript.
In this post, we have learned what is hoisting in Js. In the next post, we will practice some questions for a better grip on Hoisting, so stay tuned ๐.
Thanks for reading it๐. I hope it was insightful and you got to learn something new today. If you liked the article, please post likes and share it in your circles. Share your feedback and comment away.