Friday, March 22, 2024

What is hoisting in JavaScript?

**Hoisting in JavaScript**:

Hoisting is like when you magically lift things up. In JavaScript, it means that declarations (like variables and functions) are lifted or brought to the top of their scope during the code execution. 

**Example**:

console.log(x); // Output: undefined

var x = 10;

Explanation:

Even though we're trying to `console.log(x)` before declaring `x`, JavaScript doesn't give an error. Instead, it "hoists" the declaration of `x` to the top, which means it's like saying `var x;` is moved to the very top of the scope:

var x;

console.log(x); // Output: undefined

x = 10;

So, when we `console.log(x)` before assigning `x` a value, it outputs `undefined` because `x` exists (it's been declared), but it hasn't been assigned a value yet.