Day 1/30 - Talk JavaScript To Me: Hoisting
If you're diving into JavaScript, you've likely heard the term "hoisting." But what exactly does it mean? Let's find out!
What is Hoisting?
Hoisting is a JavaScript mechanism where variables and function declarations are moved, or "hoisted" to the top of their containing scope during the compile phase. This means you can use functions and variables before you declare them in your code. However, it's important to understand the nuances to avoid common pitfalls.
How Hoisting Works
Variable Hoisting
In JavaScript, variable declarations are hoisted to the top of their scope. However, only the declaration is hoisted, but not the initialisation.
Let's check out an example:
console.log(x); // Output: undefined
var x = 15;
console.log(x); // Output: 15
This is what happens behind the scenes:
var x; // Declaration is hoisted
console.log(x); // Output: undefined
x = 15; // Initialisation in place
console.log(x); // Output: 15
Function Hoisting
Function declarations are also hoisted to the top of their scope, allowing you to call a function before you define it.
Let's take an example:
Recommended by LinkedIn
sayHello(); // Output: "Hello, LinkedIn!"
function sayHello() {
console.log("Hello, LinkedIn!");
}
JavaScript interprets this code as:
function sayHello() { // Declaration is hoisted
console.log("Hello, LinkedIn!");
}
sayHello(); // Function call
Hoisting with let and const
'let' and 'const' declarations are hoisted but are not initialised. This results in a "temporal dead zone" where the variable exists but cannot be accessed until the declaration is encountered.
Let's take an example:
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 20;
console.log(y); // Output: 20
Best Practices to follow:
Conclusion
Hoisting can seem confusing at first, but with practice, it becomes a helpful feature in JavaScript. By understanding how hoisting works, you can write cleaner, more predictable code.
Feel free to reach out if you have any questions or want to discuss more about JavaScript and its quirks! Even if you do not agree with this post 😜
#JavaScript #Coding #WebDevelopment #Learning #BeginnerTips #Programming
Full Stack Engineer | React | Node | JavaScript | Typescript | Next | MERN Developer
10moGreat content ! It's always good to know how the language works down the hood. Have you ever faced some problem in real world where the knowledge of hosting helped to understand it better ?