Topic 16 of 37
Variable & Function Hoisting
Overview
Hoisting is JS's default behavior of moving declarations to the top of the current scope during the compile phase. This allows you to call functions before they appear in the code. However, only declarations are hoisted, not initializations.
Syntax
Function declarations allow you to organize your code with execution at the top and definitions at the bottom. Variables declared with var are hoisted but undefined.
Function vs Variable Hoisting
javascript
// Function Declarations are fully hoisted
greet(); // "Hello!"
function greet() {
console.log("Hello!");
}
// 'var' declarations are hoisted, but initialized to undefined
console.log(myVar); // undefined
var myVar = 10;
// Function Expressions are treated like variables
// sayHi(); // TypeError: sayHi is not a function (it is undefined)
var sayHi = function() { console.log("Hi"); };Common Pitfalls
- Relying heavily on 'var' hoisting leads to spaghetti code where it's hard to track what the value of a variable is at a given line.
Interview Tips
- Remember that 'let' and 'const' are hoisted too! However, they are in the Temporal Dead Zone (TDZ) and cannot be accessed until initialized.
Real-World Example
Putting helper functions at the bottom of a file for readability.
example
javascript
// Main logic is prominent at the top
initApp();
// Helpers are tucked away at the bottom
function initApp() {
setupDatabase();
startServer();
}
function setupDatabase() { /* ... */ }
function startServer() { /* ... */ }