Skip to content
jshacks.dev
Functions

What Is a First-Class Function in JavaScript

A first-class function is a function treated as a value. See how to store, pass, return and attach functions in JavaScript, with exact Node.js 24 output.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js and TypeScript logos.

A first-class function is a function that the language treats like any other value. You can put it in a variable, store it in an array or an object, pass it to another function as an argument and return it from a function, and the language does not care that it is a function and not a number or a string. JavaScript works this way, and so do Python, Ruby and Go, while older languages such as C allow only a pointer to a function and some require functions to be declared in a fixed place. The idea sounds abstract, and it is the reason that array.map(fn), event handlers, setTimeout(fn), middleware, promises and React hooks exist. This post shows the four things you can do with a function value, the terms that go with them and the one limit worth knowing, with exact output on Node.js 24.

A function is a value

JavaScript
function greet(name) {
  return "Hello, " + name;
}

console.log(typeof greet);
console.log(greet instanceof Object);

const hello = greet;

console.log(hello("Ana"));
console.log(hello === greet, hello.name);
Text
function
true
Hello, Ana
true greet

typeof greet says "function", and a function is also an object, so it can have properties. The assignment const hello = greet copies a reference to the same function, not a new function, which is why hello === greet is true and why the function's own name property still reads greet. The call is a separate step, written with parentheses: greet is the function, and greet("Ana") is the result of calling it. Forgetting the parentheses is the most common beginner mistake with this idea, since console.log(greet) prints the function itself and not its result.

1. Store functions in variables, arrays and objects

JavaScript
const operations = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b,
  multiply: (a, b) => a * b,
};

console.log(operations.add(2, 3), operations["multiply"](2, 3));

const pipeline = [(n) => n + 1, (n) => n * 2, String];

console.log(pipeline.map((step) => typeof step));
Text
5 6
[ 'function', 'function', 'function' ]

An object of functions is a lookup table, and it replaces a long if or switch chain: choose the function by key, then call it. An array of functions is a list of steps. Even built-in functions such as String are values and can sit in the list.

JavaScript
function run(operation, a, b) {
  const fn = operations[operation];

  if (!fn) throw new Error("Unknown operation: " + operation);

  return fn(a, b);
}

console.log(run("subtract", 10, 4));
Text
6

2. Pass a function as an argument

A function that receives another function is called a higher-order function, and the function it receives is often called a callback. This is the most common use of first-class functions.

JavaScript
function repeat(times, action) {
  for (let i = 0; i < times; i++) action(i);
}

repeat(3, (i) => console.log("step", i));

const numbers = [1, 2, 3, 4];

console.log(numbers.filter((n) => n % 2 === 0));
console.log(numbers.map((n) => n * n));
console.log(numbers.reduce((sum, n) => sum + n, 0));
Text
step 0
step 1
step 2
[ 2, 4 ]
[ 1, 4, 9, 16 ]
10

repeat does not know what the action does, and filter, map and reduce do not know what the test or the transformation is. They own the loop, and you own the decision. That split is why the same few array methods cover most list work: the repeated part is written once, and the part that changes is passed in.

Timers and events work the same way. setTimeout(callback, 100) stores your function and calls it later, and button.addEventListener("click", handler) keeps the handler until the click.

JavaScript
setTimeout(() => console.log("later"), 0);

console.log("first");
Text
first
later

3. Return a function from a function

A function can build and return another function. The returned function remembers the variables of the function that created it, which is called a closure.

JavaScript
function multiplier(factor) {
  return (n) => n * factor;
}

const double = multiplier(2);
const triple = multiplier(3);

console.log(double(5), triple(5));
console.log(multiplier(10)(4));
Text
10 15
40

multiplier(2) returned a new function that holds on to factor as 2, and multiplier(3) returned another one that holds 3. The two are independent. The last line calls the result immediately, with two pairs of parentheses. The closure guide on this site goes deeper into how that memory works. For now, the point is that a function can be made to order, with settings baked in, and that is the basis of partial application, middleware and decorators.

JavaScript
function once(fn) {
  let called = false;
  let result;

  return (...args) => {
    if (!called) {
      called = true;
      result = fn(...args);
    }

    return result;
  };
}

const init = once(() => {
  console.log("initializing");

  return 42;
});

console.log(init(), init());
Text
initializing
42 42

once takes a function and returns a version of it that runs only the first time. The wrapped function was never changed, and the new behavior was added around it, which is a pattern that needs functions to be values.

4. Attach properties to a function

Because a function is an object, you can give it properties, and some libraries do. Most of the time you should not, but it explains a few built-in behaviors.

JavaScript
function counter() {
  counter.calls = (counter.calls ?? 0) + 1;

  return counter.calls;
}

counter();
counter();

console.log(counter.calls, counter.length, counter.name);
Text
2 0 counter

Every function has a name and a length, which is the number of declared parameters before the first default. Properties on functions are a way to attach state, though a closure or a class is usually cleaner.

Words you will meet

TermMeaning
First-class functiona function that is a value like any other
Higher-order functiona function that takes or returns functions
Callbacka function passed in to be called later
Closurea function together with the variables it remembers
Anonymous functiona function without a name, such as an arrow passed inline
Pure functiona function whose result depends only on its arguments, with no side effects

These terms overlap, and one function can be several of them at once. multiplier is higher-order because it returns a function, and the function it returns is a closure.

What first-class does not mean

It does not mean that functions behave like data in every way. You cannot compare two functions by what they do, only by identity, so two separate functions with the same body are not equal. And functions cannot be copied by structuredClone or written to JSON.

JavaScript
const a = (x) => x + 1;
const b = (x) => x + 1;

console.log(a === b, a === a);
console.log(JSON.stringify({ fn: a, n: 1 }));

try {
  structuredClone({ fn: a });
} catch (error) {
  console.log(error.name);
}
Text
false true
{"n":1}
DataCloneError

JSON.stringify drops function properties silently, and structuredClone refuses them with a DataCloneError. If you need to send behavior across a boundary, send a name and look the function up in a table on the other side, which is the lookup table pattern from earlier.

Why it matters in practice

First-class functions let you write less code for the same job, and they change how you design programs. Instead of a class hierarchy with an overridden method, you pass the one function that differs. Instead of copying a loop with a different test, you write the loop once. Instead of a flag that changes a function's behavior, you pass the behavior. The cost is that code which passes functions around can be harder to follow in a debugger, so name the functions that matter, so that a stack trace says validateEmail and not anonymous.

Where the idea stops

First-class functions are not free of trouble. Callbacks nested several levels deep are hard to read, which is the reason promises and async functions exist. A function that captures a large object in its closure keeps that object in memory as long as the function is reachable. And functions passed around need documentation of what they receive and what they should return, since the language does not check it, and a TypeScript type for the callback is the usual answer.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read
Flat illustration of two options weighed side by side, with the JavaScript, Node.js and npm logos.
Functions

Arrow Functions vs Regular Functions

Arrow functions vs regular functions compared on this, arguments, new, prototype, hoisting and class fields, with exact output and a rule for choosing.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.