Calling Functions Before Declaration
You'll learn when you can actually call a function before you define it in your code.
Based on what you learned about function declaration hoisting, JavaScript moves function declarations to the top of their scope before running any code. This means you can safely call a declared function before its definition appears in the file — and your code will work perfectly.
Why This Works
// This works fine!
greet("Alice"); // "Hello, Alice!"
function greet(name) {
return "Hello, " + name + "!";
}
JavaScript reads through your code in two passes. During the first pass, it hoists all function declarations to the top. By the time the second pass runs your code line-by-line, the function already exists in memory — even though you wrote the call first.
When It Doesn't Work
Remember that function expressions don't get hoisted this way:
// This breaks!
sayHi("Bob"); // Error: sayHi is not a function
var sayHi = function(name) {
return "Hi, " + name + "!";
};
The variable sayHi is hoisted, but its assignment happens when code execution reaches that line. Before that, sayHi is undefined.
Practical Use
Many developers prefer writing helper functions at the bottom of a file and main logic at the top, making the important code more visible:
processUserData(); // Called first, defined below
function processUserData() {
// main logic here
}
Key Takeaway: Function declarations can be called before they appear in your code thanks to hoisting, but function expressions cannot — they must be defined before use.