Sub topic 9
Function Declarations Versus Function Expressions
This chapter assumes you already know how var is hoisted during the creation phase of a scope, and that you can write and call functions. You will see why some functions can be called before the line that defines them while others fail, and what kind of error you get when it goes wrong.
Two Ways to Create a Function
A function declaration is a statement that starts with the function keyword and gives the function a name:
function add(a, b) {
return a + b;
}A function expression creates a function as a value and usually assigns it to a variable. Arrow functions are always expressions.
const add = function (a, b) {
return a + b;
};
const multiply = (a, b) => a * b;Both forms give you a callable add, but the engine handles them differently during the creation phase.
What Gets Hoisted
During the creation phase, the engine registers every function declaration in the scope along with its body. So the function is ready to call from the first line of that scope.
A function expression is hoisted only as far as its variable. The function value is created when execution reaches the assignment. Until that line runs, the variable holds whatever its declaration keyword gives it before initialization.
greet(); // "hi"
function greet() {
console.log("hi");
}
try {
sayBye();
} catch (e) {
console.log(e.name); // "TypeError"
}
var sayBye = function () {
console.log("bye");
};sayBye exists because var was hoisted, but its value is undefined. Calling undefined throws a TypeError, which is different from a missing-name error.
Expressions with let and const
Most modern code assigns function expressions with const. An early call then fails with a ReferenceError, because the binding exists but has not been initialized yet. The next chapter covers this behavior in detail.
try {
double(4);
} catch (e) {
console.log(e.name); // "ReferenceError"
}
const double = (n) => n * 2;
console.log(double(4)); // 8| Form | Hoisted as | Early call result |
|---|---|---|
| `function f() {}` | Name and body | Works |
| `var f = function () {}` | Name, value `undefined` | TypeError |
| `let`/`const f = () => {}` | Name, uninitialized | ReferenceError |
Named Function Expressions
A function expression can have its own name. That name is visible only inside the function body, which makes it useful for recursion and for clearer stack traces.
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(5)); // 120
console.log(typeof fact); // "undefined"Common Errors
- Reading a TypeError as "not defined".
x is not a functionusually means avar-assigned expression was called too early, or the variable holds some other value. - Reordering code. Moving a declaration into a
constexpression can break callers that sit above it. Check the call sites before converting. - Declarations inside blocks. In strict mode and in modules, a function declared inside an
ifblock is scoped to that block. Sloppy mode has legacy rules that make it partly visible outside the block. Avoid relying on either behavior.
Exercise
In a script, the code is: run(); var run = function () { console.log("ok"); }; function run() { console.log("decl"); } What does it log, and why?
Show answer
It logs "decl". During the creation phase the function declaration binds run to its body, and the var declaration of the same name does not reset it. The call happens before the assignment line, so the declaration's body runs. The expression replaces run only after that line executes.
Exercise
You call format() before const format = () => "x"; in the same scope. Which error is thrown, and how would it differ with var?
Show answer
A ReferenceError, because the const binding is uninitialized at that point. With var the binding would be undefined, so the call would throw a TypeError instead.