Hoisting in JavaScript means that variable and function declarations are moved to the top of their scope (before the code runs). This means you can use a variable or function before it is declared.
Example of Hoisting with var
console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5
Explanation:
JavaScript "hoists" the var x declaration to the top, so the first console.log(x) doesn’t throw an error.
However, only the declaration is hoisted, not the assignment. That's why the first console.log(x) shows undefined.
Example of Function Hoisting
sayHello(); // Output: Hello!
function sayHello() {
console.log("Hello!");
}
Explanation:
In the case of functions, the entire function is hoisted. That’s why sayHello() works even though the function is defined after it is called.
Note:
let and const are also hoisted, but they are not initialized (you’ll get an error if you use them before declaring).
No comments:
Post a Comment