Function Expressions
A function expression is a function created inside an expression, usually to store it in a variable or pass it to another function: const lateFee = function (days) { ... };. It produces the same kind of function as a declaration, but it is created when that line runs, not before. Function expressions are how JavaScript code passes behavior around: to array methods, to event listeners, to timers.
In One Minute
const name = function (params) { ... };stores a function in a variable.- An expression can be anonymous or named:
const f = function g() { ... }. The namegis visible only inside the function, which is useful for recursion and stack traces. - Unlike declarations, function expressions aren't usable before their line runs.
- Functions are values: store them in objects and arrays, pass them as arguments, return them from functions.
- Arrow functions (next lesson) are a shorter form of function expression.
Declaration vs Expression
Syntax
// Function declaration: a statement starting with the keyword function
function lateFee(days) {
return days * 2;
}
// Function expression: a function used as a value
const lateFee2 = function (days) {
return days * 2;
};Note the semicolon after the expression's closing brace: the whole line is a const statement.
Example
const formatUsd = function (amount) {
return "$" + amount.toFixed(2);
};
console.log(formatUsd(120));
console.log(typeof formatUsd);
console.log(formatUsd.name);$120.00
function
formatUsdExplanation: the function has no name of its own, but JavaScript infers its name property from the variable it is assigned to. That inferred name appears in stack traces, which makes debugging easier.
| Function declaration | Function expression | |
|---|---|---|
| Form | function f() {} as a statement | const f = function () {}; |
| Usable before its line | Yes (hoisted) | No |
| Can be anonymous | No | Yes |
| Can be reassigned | Yes (avoid it) | Not if stored in a const |
| Typical use | Top-level helpers in a file | Callbacks, functions stored in objects, conditional definitions |
Hoisting Difference
A declaration can be called before the line where it is written. An expression stored in const or let can't:
console.log(declared(2));
try {
console.log(expressed(2));
} catch (err) {
console.log(err.name + ": " + err.message);
}
function declared(x) {
return x * 10;
}
const expressed = function (x) {
return x * 10;
};20
ReferenceError: Cannot access 'expressed' before initializationThe const variable exists from the start of its scope but can't be used until its line runs (the "temporal dead zone", explained in the hoisting lesson). Some teams prefer expressions for exactly this reason: code reads top to bottom, and nothing is used before it is defined.
Named Function Expressions
A function expression can have its own name. The name is visible only inside the function body:
const countdown = function tick(n) {
if (n === 0) return "Go!";
return n + " " + tick(n - 1);
};
console.log(countdown(3));
console.log(typeof tick);3 2 1 Go!
undefinedExplanation: inside the function, tick refers to the function itself, so it can call itself (recursion) even if the outer variable countdown is later reassigned. Outside, tick doesn't exist. Named expressions also show their own name in stack traces, which helps when the function is anonymous otherwise, such as a callback.
Passing Functions as Arguments
Function expressions are most often written right where they are needed, as an argument:
const fees = [120, 85, 450, 45];
const large = fees.filter(function (fee) {
return fee >= 100;
});
console.log(large);
const sorted = [...fees].sort(function (a, b) {
return a - b;
});
console.log(sorted);
setTimeout(function remind() {
console.log("Reminder sent");
}, 0);
console.log("Timer scheduled");[120, 450]
[45, 85, 120, 450]
Timer scheduled
Reminder sentEach function expression here is a callback: filter calls it once per item, sort calls it to compare pairs, and setTimeout calls it later. In modern code, most of these short callbacks are written as arrow functions, as the next lesson shows.
Storing Functions in Objects and Arrays
Because functions are values, data structures can hold them. A lookup table of functions is a clean alternative to a long switch:
const discountRules = {
none: function (amount) { return amount; },
sibling: function (amount) { return amount * 0.9; },
staff: function (amount) { return amount * 0.5; },
};
for (const rule of ["none", "sibling", "staff"]) {
console.log(rule, discountRules[rule](450));
}
const steps = [
function (x) { return x + 10; },
function (x) { return x * 2; },
];
let value = 5;
for (const step of steps) value = step(value);
console.log(value);none 450
sibling 405
staff 225
30discountRules[rule](450) first looks up a function by name, then calls it. Functions stored as properties of an object are called methods, covered in the objects chapter.
Returning Functions
A function can create and return another function. The returned function remembers the variables of the function that created it:
function makeLateFee(ratePerDay) {
return function (days) {
return days * ratePerDay;
};
}
const standard = makeLateFee(2);
const strict = makeLateFee(5);
console.log(standard(10));
console.log(strict(10));20
50Explanation: makeLateFee(2) returns a new function that still sees ratePerDay = 2 after makeLateFee has finished. Each call to makeLateFee creates a separate function with its own remembered rate. This "remembering" is called a closure, one of the most important ideas in JavaScript, with a full lesson later. A function that takes or returns functions is called a higher-order function.
In Practice
The Fee Tracker picks a formatting function once, based on settings, then uses it everywhere. Code that formats amounts doesn't need to know which style was chosen:
function chooseFormatter(style) {
if (style === "plain") {
return function (cents) { return (cents / 100).toFixed(2); };
}
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
return function (cents) { return usd.format(cents / 100); };
}
const settings = { style: "currency" };
const format = chooseFormatter(settings.style);
const payments = [12000, 8550, 123450];
console.log(payments.map(format).join(" | "));
console.log(payments.map(chooseFormatter("plain")).join(" | "));$120.00 | $85.50 | $1,234.50
120.00 | 85.50 | 1234.50Common Mistakes
Calling an expression before its line. ReferenceError: Cannot access ... before initialization. Move the call below, or use a declaration.
Forgetting the semicolon after an expression. Usually harmless thanks to automatic semicolon insertion, but a following line starting with ( or [ joins onto it. Write the semicolon.
Passing fn() instead of fn. The call runs immediately and passes its result.
Using the inner name of a named expression outside it. It exists only inside the function body.
Practice
Challenge: Write makeCounter(start) that returns a function; each call to the returned function returns the next number, starting at start. Create two counters and show that they count independently.
Show solution
function makeCounter(start) {
let next = start;
return function () {
const current = next;
next += 1;
return current;
};
}
const receipts = makeCounter(100);
const tickets = makeCounter(1);
console.log(receipts(), receipts(), receipts());
console.log(tickets(), tickets());100 101 102
1 2Key Takeaways
| Form | Example |
|---|---|
| Anonymous expression | const f = function (x) { ... }; |
| Named expression | const f = function step(x) { ... }; |
| Callback | arr.filter(function (x) { ... }) |
| Function in an object | { apply: function (x) { ... } } |
| Returned function | return function (x) { ... }; |
Was this tutorial helpful?