Sub topic 9
Function Declarations Versus Function Expressions
JavaScript gives you several ways to create a function, and they do not all become available at the same moment. A function declaration can be called on a line above the place where it is written. A function expression usually cannot. This chapter explains the reason for that difference, what goes wrong when you mix the two forms, and how to pick one deliberately.
This chapter assumes you already know how to write and call functions, and that you have read the earlier chapters on the creation and execution phases of a scope and on var hoisting. The temporal dead zone for let and const gets its own chapter next. Here it comes up only where it affects function expressions.
Two Ways to Write 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;
}
console.log(add(2, 3)); // 5A function expression creates a function as a value inside a larger expression. Usually that value is assigned to a variable:
const multiply = function (a, b) {
return a * b;
};
const subtract = (a, b) => a - b; // an arrow function is also an expression
console.log(multiply(2, 3)); // 6
console.log(subtract(5, 2)); // 3Both forms give you a callable function. The difference is in what the engine does with them during the creation phase.
What Gets Hoisted, and How Much
When a scope is set up, the engine scans it for declarations before it runs any code. A function declaration is handled completely during that scan: the engine creates the name and binds it to the finished function object. The body is ready before the first line of the scope runs.
A function expression is not a declaration. Nothing happens to it during the creation phase. Only the variable that will hold it is processed, and that variable follows the rules of its own keyword (var, let, or const). The function object itself is created only when execution reaches the assignment.
greet(); // "hi"
function greet() {
console.log("hi");
}
try {
sayBye();
} catch (e) {
console.log(e.name); // "TypeError"
}
var sayBye = function () {
console.log("bye");
};greet() works because the declaration was fully hoisted. sayBye() fails with a TypeError, not a ReferenceError. The name sayBye exists, because var hoisted it and initialized it to undefined. Calling undefined as a function is a type error, and Node.js reports it as sayBye is not a function.
Expressions held by let and const
Most modern code assigns function expressions with const. An early call then fails in a different way:
try {
early();
} catch (e) {
console.log(e.name); // "ReferenceError"
}
const early = () => "ready";
console.log(early()); // "ready"The const binding exists from the start of the scope, but it is uninitialized until its declaration line runs. Touching it before then throws a ReferenceError. That is the temporal dead zone, which the next chapter covers in detail. For now, remember which error points to which cause:
| Error on early call | Likely cause |
|---|---|
| `TypeError: x is not a function` | `var x = function ...` called before assignment, or `x` holds a non-function value |
| `ReferenceError: Cannot access 'x' before initialization` | `let`/`const x = ...` called before its declaration line |
| `ReferenceError: x is not defined` | No declaration of `x` in any reachable scope |
Comparing the Forms
| Form | Hoisted name? | Initial value | Callable before its line? | Block scoped? |
|---|---|---|---|---|
| `function f() {}` | Yes | The function | Yes | In strict mode, yes (see below) |
| `var f = function () {}` | Yes | `undefined` | No, `TypeError` | No |
| `let f = function () {}` | Yes | Uninitialized | No, `ReferenceError` | Yes |
| `const f = () => {}` | Yes | Uninitialized | No, `ReferenceError` | Yes |
| `class C {}` | Yes | Uninitialized | No, `ReferenceError` | Yes |
Classes are included because developers often expect them to behave like function declarations, since a class is a kind of function internally. They do not. Class declarations behave like let.
Named Function Expressions
A function expression can have its own name:
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(5)); // 120
console.log(typeof fact); // "undefined"The name fact is visible only inside the function's own body. It is not added to the surrounding scope, which is why typeof fact outside reports "undefined". This has two practical uses:
- Safe recursion. The function refers to itself through
fact, which cannot be reassigned from outside. If someone later reassignsfactorial, the recursion still works. - Better stack traces. Debuggers show
factin the call stack. Modern engines also infer names for anonymous functions assigned to variables (factorial.namewould be"factorial"without the inner name), so this matters most for callbacks passed inline, such assetTimeout(function retry() { ... }, 100).
Inside its own body the inner name works like a constant. In strict mode, assigning to fact inside the function throws a TypeError. In sloppy mode, the assignment is silently ignored.
Name Collisions Between Declarations
Because function declarations are processed in the creation phase, they interact with other declarations of the same name in ways that can surprise you.
A function and a var with the same name
console.log(typeof value); // "function"
var value = 1;
function value() {}
console.log(typeof value); // "number"During creation, var value reserves the name, and the function declaration binds it to the function. A var without an initializer never overwrites an existing binding with undefined, so the function wins at first. Then execution reaches value = 1, and the number replaces the function. The function declaration line does nothing at execution time, because its work is already done.
Using let or const with the same name as a function declaration in the same scope is a SyntaxError. The whole script refuses to run. That early failure is a good reason to prefer those keywords.
Two declarations with the same name
speak(); // "second"
function speak() {
console.log("first");
}
function speak() {
console.log("second");
}Both declarations are processed in source order during creation, so the last one wins, even for a call written above both. Linters flag this as no-redeclare or no-func-assign because it is almost always a mistake.
Function Declarations Inside Blocks
Declaring a function inside an if block or another block behaves differently depending on the mode.
In strict mode, which includes ES modules and class bodies, a function declared in a block is scoped to that block. It is hoisted to the top of the block with its body, and it is invisible outside:
"use strict";
if (true) {
console.log(typeof helper); // "function" (hoisted within the block)
function helper() {}
}
console.log(typeof helper); // "undefined"In sloppy mode, browsers kept an older, legacy behavior for compatibility. The specification describes it in Annex B. The function also gets a var-like binding in the enclosing function or script. That binding starts as undefined and receives the function only when the block runs:
// Run as a plain (non-module) script in sloppy mode
console.log(typeof legacy); // "undefined"
if (true) {
function legacy() {}
}
console.log(typeof legacy); // "function"If the condition is false, legacy stays undefined outside the block. The same source code therefore behaves differently depending on whether the file is a module, whether it has "use strict", and which branch ran.
Choosing Between the Forms
Both forms are valid. Teams usually choose one of these approaches on purpose:
- Declarations for top-level helpers. Because they are fully hoisted, you can put the main logic at the top of a file and the helper functions below it, so the file reads from the overview down to the details. Mutually recursive functions (
isEvencallsisOdd, which callsisEven) work no matter which one comes first. constexpressions everywhere. The function cannot be reassigned, it cannot be used before its definition, and it follows the same block scoping as every otherconst. Code reads strictly top to bottom, and an out-of-order call fails loudly instead of quietly.- Arrow functions for callbacks and short helpers. Arrow functions are always expressions, so they follow the variable's hoisting rules. They also differ in
thisandargumentsbinding, which is outside the scope of this chapter.
Avoid var f = function () {} in new code. It combines the worst parts of both forms: an early call does not fail at the declaration but later at the call site, with a vague TypeError, and the name can be reassigned without warning.
const run = () => helper(); // helper is referenced, not called yet
const helper = () => "done";
console.log(run()); // "done"Exercises
Exercise
What does this code print, and why? console.log(typeof calc); var calc = 10; function calc() {} console.log(typeof calc);
Show answer
It prints "function" and then "number". During the creation phase, the function declaration binds calc to the function, and the var declaration without an initializer does not overwrite it. At execution time, the assignment calc = 10 replaces the function with a number. The function declaration line does nothing at execution time.
Exercise
A colleague's code throws "TypeError: render is not a function" on a call near the top of a file, while render is defined further down. Another file throws "ReferenceError: Cannot access 'render' before initialization". What form of definition does each file most likely use, and what is one fix for both?
Show answer
The first file most likely uses var render = function ... (or an arrow function assigned with var), so render is hoisted as undefined. The second uses const or let, so render is in its temporal dead zone. One fix for both is to move the call below the definition. Another is to convert render into a function declaration, which is hoisted together with its body.
Exercise
Given const countdown = function tick(n) { if (n > 0) tick(n - 1); return n; };, what is typeof tick outside the function, and what advantage does calling tick inside the body have over calling countdown?
Show answer
typeof tick outside is "undefined", because the name of a named function expression exists only inside its own body. Calling tick for recursion keeps working even if the countdown variable is later reassigned or shadowed, since tick always refers to this function object.
Exercise
Why might if (flag) { function setup() {} } setup(); work in one file and throw in another, with no change to the code?
Show answer
Block-level function declarations depend on the mode. In sloppy-mode scripts, Annex B semantics create a var-like binding for setup in the enclosing scope, assigned when the block runs, so the call works if flag is true. If flag is false, the call throws a TypeError. In strict mode or an ES module, setup is scoped to the block, so the call outside throws a ReferenceError.