Function Expression Hoisting Behavior
What you'll learn: How function expressions behave differently from declarations when JavaScript hoists variables during execution.
The Key Difference
You've already learned that function declarations are fully hoisted — meaning you can call them before they appear in your code. Function expressions work differently because they follow variable hoisting rules, not function hoisting rules.
When you write a function expression, JavaScript hoists the variable declaration but not the function assignment. The variable exists from the top of the scope, but it's undefined until the line where you assign the function to it.
How It Works
// This causes an error!
console.log(greet); // undefined (variable is hoisted)
greet(); // TypeError: greet is not a function
var greet = function() {
return "Hello!";
};
JavaScript effectively sees it like this:
var greet; // Declaration hoisted to top
console.log(greet); // undefined
greet(); // Trying to call undefined — error!
greet = function() { // Assignment happens here
return "Hello!";
};
The Analogy
Think of it like a parking space. With a declaration, the car (function) is already parked when you arrive. With an expression, the parking space (variable) is reserved, but empty — the car doesn't arrive until later in the timeline.
Practical Impact
You must define function expressions before you use them. The order of your code matters:
greet(); // Works now!
var greet = function() {
return "Hello!";
};
Key Takeaway: Function expressions are not hoisted as functions — only their variable names are hoisted (as undefined), so you cannot call them before the assignment line runs.