49. Function Hoisting
Hoisting is JavaScript's behavior of moving declarations (but not the assignments) to the top of the current scope during compilation.
1. Function Declaration Hoisting
The entire function definition is hoisted, meaning you can call the function anywhere in the scope, even before its definition.
javascript hello(); // Output: 'Function works!'
function hello() { console.log('Function works!'); }
2. var Variable Hoisting
Only the declaration (var name;) is hoisted, but the assignment (= 'Value') stays put. The variable is initialized with undefined.
javascript console.log(x); // Output: undefined (not an error!) var x = 5;
3. let and const Hoisting
let and const are technically hoisted, but they are put in a state called the Temporal Dead Zone (TDZ) until their declaration line is reached. Accessing them in the TDZ results in a ReferenceError.
javascript // console.log(y); // ERROR: Cannot access 'y' before initialization (TDZ) let y = 5;
Conclusion: Rely on function hoisting if you must, but always declare let/const variables before you use them.