Hoisting is a behavior in JavaScript where 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:
- 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 "var", it will exist in memory with a default value of "undefined" 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.
- 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 "Hello World!" to the console, even though "๐ฆ๐ฒ๐ ๐ฎ๐ง๐" is called before its actual declaration in the code.
- 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: Cannot access 'myVar' before initialization
let myVar = 5;
If you try to access the value of a variable declared with let or const before it has been initialized, JavaScript will throw a ReferenceError with the message "Cannot access 'myVar' before initialization".
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.
Let's connect on LinkedIn. I'd love to connect :)
Top comments (0)