Hoisting In Javascript ( Part - 1 ): How to stay on Top of Your Code.

Hoisting In Javascript ( Part - 1 ): How to stay on Top of Your Code.

ยท

2 min read

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.

ย