Sub topic 3
Function Expressions
This chapter assumes you know basic JavaScript syntax, how let and const declare variables, and how to call a function with arguments. It also builds on the previous chapter's point that functions are values.
A function expression is a function created with the function keyword in a place where JavaScript expects a value. The result is a function object. You can store it in a variable, pass it to another function, or return it.
The basic form
const multiply = function (a, b) {
return a * b;
};
console.log(multiply(2, 3)); // 6
console.log(typeof multiply); // "function"The right side of = is a function expression. It has no name of its own, so it is an anonymous function expression. The variable multiply holds a reference to the function. The trailing semicolon ends the const statement, the same as it would for const x = 5;.
Declaration or expression: position decides
The same function keyword can produce a declaration or an expression. The parser decides which by where the keyword appears.
So an anonymous function () {} at the start of a line is a SyntaxError, because a declaration needs a name. Wrapping the same code in parentheses turns it into an expression. A later chapter on immediately invoked function expressions relies on that trick.
Where function expressions show up
Function expressions are useful anywhere a function is needed only as a value:
// Passed as an argument
const doubled = [1, 2, 3].map(function (n) {
return n * 2;
});
console.log(doubled); // [ 2, 4, 6 ]
// Returned from another function
function makeAdder(x) {
return function (y) {
return x + y;
};
}
const addTen = makeAdder(10);
console.log(addTen(5)); // 15
// Stored as an object property
const math = {
square: function (n) {
return n * n;
}
};
console.log(math.square(4)); // 16The function returned by makeAdder keeps access to x after makeAdder has returned. That stored access is called a closure. You get it whenever you create a function inside another function.
Name inference
An anonymous function expression assigned to a variable or property still gets a name property. JavaScript infers it from the assignment target:
const multiply = function (a, b) {
return a * b;
};
const math = { square: function (n) { return n * n; } };
console.log(multiply.name); // "multiply"
console.log(math.square.name); // "square"
console.log((function () {}).name); // ""Stack traces use this inferred name. Inference only happens at the point of assignment, though. A function passed straight into map stays anonymous. Named function expressions, covered later, fix that.
Common errors
| Mistake | What happens |
|---|---|
| Calling the variable before the line that assigns it | `ReferenceError` with `const`/`let`, `TypeError` with `var` (see the hoisting chapter) |
| Writing an anonymous `function () {}` as a statement | `SyntaxError`: function statements require a name |
| Leaving out the semicolon before a line that starts with `(` | The next line is parsed as a call to your function |
The last one is easy to miss:
try {
const greet = function () {
return 'hi';
}
(function () {
console.log('setup');
})();
} catch (e) {
console.log(e instanceof TypeError); // true
}Without the semicolon, JavaScript reads function () { return 'hi'; }(...) as one expression. It calls the first function, gets 'hi', and then tries to call 'hi'(). 'setup' never prints.
Exercise
What does this code log, and why? const f = function () { return 1; }; const g = f; console.log(g.name, g());
Show answer
It logs f 1. The anonymous function got the inferred name "f" when it was first assigned to f. Assigning it to g copies the reference to the same function object and does not rename it, so g.name is still "f" and calling it returns 1.
Exercise
Rewrite function triple(n) { return n * 3; } as an anonymous function expression stored in a constant, and explain one behavior that changes.
Show answer
const triple = function (n) { return n * 3; }; The function can no longer be called before this line runs. Until the assignment executes, triple is in the temporal dead zone, so calling it throws a ReferenceError.