Function Declaration Hoisting
What you'll learn: How function declarations become available throughout their entire scope, even before the line where they're written.
The Magic of Function Declarations
Remember how var declarations are hoisted but their values aren't? Function declarations work differently—they're fully hoisted, meaning both the name and the entire function body are available from the top of their scope.
This is why you can call a function before you've declared it in your code:
greet(); // "Hello!" — this works!
function greet() {
console.log("Hello!");
}
JavaScript moves the entire function greet() {...} declaration to the top during the creation phase, so it's ready to use immediately.
How It Works
When JavaScript sets up a scope, it processes function declarations first, making them available everywhere in that scope:
console.log(typeof sayGoodbye); // "function" — already exists!
function sayGoodbye() {
console.log("Goodbye!");
}
Compare this to var, where only the declaration is hoisted:
console.log(typeof myVar); // "undefined" — declared but not initialized
var myVar = 10;
Why This Matters
Function declaration hoisting lets you organize code naturally—you can put helper functions at the bottom of a file while calling them at the top, making your main logic easier to read.
start(); // This reads naturally at the top
function start() {
console.log("Program starting...");
}
Key Takeaway: Function declarations are fully hoisted—both name and body—letting you call them anywhere in their scope, even before they appear in your code.