Function Expressions

Updated · 7 min read
easyES2026javascriptfunctionsfunction-expressionscallbacks

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 name g is 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

syntax.js
// 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

expression.js▶ Try it
const formatUsd = function (amount) {
  return "$" + amount.toFixed(2);
};
 
console.log(formatUsd(120));
console.log(typeof formatUsd);
console.log(formatUsd.name);
Output
$120.00
function
formatUsd

Explanation: 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 declarationFunction expression
Formfunction f() {} as a statementconst f = function () {};
Usable before its lineYes (hoisted)No
Can be anonymousNoYes
Can be reassignedYes (avoid it)Not if stored in a const
Typical useTop-level helpers in a fileCallbacks, 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:

hoisting.js▶ Try it
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;
};
Output
20
ReferenceError: Cannot access 'expressed' before initialization

The 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:

named.js▶ Try it
const countdown = function tick(n) {
  if (n === 0) return "Go!";
  return n + " " + tick(n - 1);
};
 
console.log(countdown(3));
console.log(typeof tick);
Output
3 2 1 Go!
undefined

Explanation: 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:

callbacks.js▶ Try it
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");
Output
[120, 450]
[45, 85, 120, 450]
Timer scheduled
Reminder sent

Each 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:

table.js▶ Try it
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);
Output
none 450
sibling 405
staff 225
30

discountRules[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:

factory.js▶ Try 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));
Output
20
50

Explanation: 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:

formatter.js▶ Try it
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(" | "));
Output
$120.00 | $85.50 | $1,234.50
120.00 | 85.50 | 1234.50

Common 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
counter.js▶ Try it
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());
Output
100 101 102
1 2

Quick check: Function expressions

3 questions
1What happens when you call a const function expression before its line?
2In const f = function g() {}, where can the name g be used?
3What does makeLateFee(2) return in this lesson?

Key Takeaways

FormExample
Anonymous expressionconst f = function (x) { ... };
Named expressionconst f = function step(x) { ... };
Callbackarr.filter(function (x) { ... })
Function in an object{ apply: function (x) { ... } }
Returned functionreturn function (x) { ... };

Was this tutorial helpful?

Lesson 29 of 139