Skip to content
jshacks.dev
Functions

The Complete Guide to Functions in JavaScript

A complete guide to JavaScript functions: every way to define one, parameters, return values, this, closures, callbacks, recursion, async code and design rules.

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

Almost everything you write in JavaScript is a function, or is called by one. A button click runs a function, a request handler is a function, a promise resolves into a function, a class is a function with extra rules, and a module is a file full of functions that other files import. Learning to write them well is the highest-return skill in the language, and it is also where most of the surprising behavior lives: the value of this, the order in which defaults are evaluated, what a closure remembers, why a callback runs later than the line that registered it. This guide covers all of it in one place. It starts with what a call actually does, goes through every way to define a function, then parameters, return values, scope and closures, this, functions as values, recursion, asynchronous functions, errors and the design rules that keep a codebase readable. Every example shows the exact output on Node.js 24, and every section ends where the advice stops. Where another post on this site goes deeper on one subject, such as closures, generators or functional programming, the guide gives the working version and points to it.

What a function call does

A function is a named or anonymous block of code that you can run on demand, with inputs and an output. The mechanics are simple and worth stating plainly, since every later section builds on them. When you call a function, the engine creates a new scope for that call, binds the parameters to the arguments you passed, runs the body from the top and stops at the first return or at the closing brace. The call expression then evaluates to the returned value, or to undefined if the body finished without one.

JavaScript
function add(a, b) {
  const total = a + b;

  return total;
}

const result = add(2, 3);

console.log(result);
console.log(add(10, 5) * 2);
Text
5
30

Three things happened on the first call. A scope was created with a as 2 and b as 3. The body ran, creating total. And return total ended the call and handed 5 back. When the call ended, that scope was normally discarded, and each later call gets a brand new one. That is why two calls to the same function do not see each other's local variables, unless a closure keeps a scope alive, which a later section covers.

The call stack is where the engine records which function is running and where to return to. A call adds a frame, and a return removes it. That is the reason a function that calls itself forever fails with a RangeError: Maximum call stack size exceeded, and the reason a stack trace in an error message lists the chain of calls that led to the failure, innermost first.

Ways to define a function

JavaScript has more syntax for functions than most languages. The forms differ in when they exist, what this means inside them and what you can do with them, so it pays to know all of them.

Function declarations

JavaScript
function square(n) {
  return n * n;
}

console.log(square(4), square.name);
Text
16 square

A declaration starts with the function keyword and a required name, and it is hoisted: the engine creates it, with its whole body, before running any code in the scope, so you can call it above the line where it is written. That makes declarations a good fit for helpers at the top level of a module, since the main code can come first and the helpers below it.

Function expressions

JavaScript
const cube = function (n) {
  return n * n * n;
};

const factorial = function fact(n) {
  return n <= 1 ? 1 : n * fact(n - 1);
};

console.log(cube(3), factorial(5), cube.name, factorial.name);
Text
27 120 cube fact

An expression is a function in a position where a value is expected, usually on the right side of an assignment or as an argument. It exists only after the line runs, and it can have its own name, visible only inside itself, which makes recursion safe even if the outer variable is later reassigned. When you assign an anonymous function to a variable, the engine infers the name from the variable, as cube.name shows.

Arrow functions

JavaScript
const double = (n) => n * 2;
const sum = (a, b) => a + b;
const makePoint = (x, y) => ({ x, y });
const log = (message) => {
  console.log(message);
};

console.log(double(4), sum(1, 2), makePoint(1, 2));
log("done");
Text
8 3 { x: 1, y: 2 }
done

Arrow functions are the short form. With no braces, the expression after => is the return value, and an object literal in that position needs parentheses so that the braces are not read as a block. They have no this, arguments or prototype of their own and cannot be used with new, which makes them ideal for callbacks and wrong for methods and constructors. A separate post compares the three forms in full.

Methods, getters and setters

JavaScript
const account = {
  owner: "Ana",
  balance: 100,
  deposit(amount) {
    this.balance += amount;

    return this;
  },
  get summary() {
    return `${this.owner}: ${this.balance}`;
  },
  set nickname(value) {
    this.owner = value;
  },
};

account.deposit(50).deposit(25);
account.nickname = "Ana B.";

console.log(account.summary);
Text
Ana B.: 175

The shorthand name() {} inside an object literal or a class defines a method, which has its own this and cannot be used with new. get and set define accessor properties: reading account.summary calls the getter, and assigning to account.nickname calls the setter, with no parentheses at the call site. Returning this from a method, as deposit does, allows chaining calls.

Classes and constructors

JavaScript
class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  area() {
    return this.width * this.height;
  }

  static square(side) {
    return new Rectangle(side, side);
  }
}

console.log(new Rectangle(2, 3).area(), Rectangle.square(4).area());
console.log(typeof Rectangle);
Text
6 16
function

A class is a function with stricter rules: it must be called with new, its body is strict, and its methods are not enumerable. typeof says "function" because that is what a class is. The older way to build the same thing was a regular function used as a constructor with methods added to its prototype, and you will still meet it in older code.

Generators and async functions

JavaScript
function* countTo(limit) {
  for (let i = 1; i <= limit; i++) yield i;
}

async function delayed(value) {
  await new Promise((resolve) => setTimeout(resolve, 5));

  return value;
}

console.log([...countTo(3)]);
console.log(await delayed("later"));
Text
[ 1, 2, 3 ]
later

function* makes a generator, which pauses at each yield and resumes when asked for the next value. async makes a function that always returns a promise and lets you use await inside it. Both have their own sections later, and the generators guide covers the first in depth.

Immediately invoked function expressions

JavaScript
const config = (() => {
  const secret = "hidden";

  return { mode: "production", reveal: () => secret.length };
})();

console.log(config.mode, config.reveal());
Text
production 6

A function that is defined and called at once creates a private scope. Before modules existed, it was the standard way to avoid leaking variables into the global scope. It is still useful for a computation that needs temporary variables and returns one value, though a plain function that you name and call is often clearer.

Parameters and arguments

Parameters are the names in the function definition. Arguments are the values passed at the call. JavaScript does not check that the numbers match: missing arguments are undefined, and extra ones are ignored, except that the function can still reach them.

JavaScript
function show(a, b) {
  return [a, b];
}

console.log(show(1), show(1, 2, 3));
Text
[ 1, undefined ] [ 1, 2 ]

This leniency is a source of bugs, and TypeScript or runtime checks are the usual cure. The next sections show the tools the language gives for handling parameters on purpose.

Default values

JavaScript
function greet(name = "friend", punctuation = "!") {
  return `Hello, ${name}${punctuation}`;
}

console.log(greet(), greet("Ana"), greet(undefined, "?"), greet(null));
Text
Hello, friend! Hello, Ana! Hello, friend? Hello, null!

A default applies when the argument is missing or undefined, and not for null. The default expression runs at each call, left to right, and can use earlier parameters. The post on default parameters covers the evaluation order and the scope rules in detail.

Rest parameters

JavaScript
function average(first, ...others) {
  const all = [first, ...others];

  return all.reduce((sum, n) => sum + n, 0) / all.length;
}

console.log(average(2, 4, 6, 8));
Text
5

A rest parameter collects the remaining arguments into a real array and must be last. It replaces the old arguments object, which is array-like, unavailable in arrow functions and linked to the named parameters in sloppy mode.

Destructured parameters and option objects

When a function takes more than three parameters, or several optional ones, callers lose track of the order. An object parameter with destructuring gives every value a name at the call site.

JavaScript
function createUser({ name, role = "member", active = true } = {}) {
  return { name, role, active };
}

console.log(createUser({ name: "Ana", role: "admin" }));
console.log(createUser({ name: "Bo" }));
Text
{ name: 'Ana', role: 'admin', active: true }
{ name: 'Bo', role: 'member', active: true }

The = {} default lets the function be called with no argument at all, and the defaults inside the pattern fill in the missing properties. This is the standard shape for functions with options, and it makes adding a new option a compatible change, since existing callers do not break.

Validating arguments

JavaScript will not stop a caller from passing the wrong thing, so a function that must be correct checks its input at the top and fails early with a message that names the problem.

JavaScript
function percentOf(part, whole) {
  if (!Number.isFinite(part) || !Number.isFinite(whole)) {
    throw new TypeError("part and whole must be finite numbers");
  }

  if (whole === 0) throw new RangeError("whole must not be zero");

  return (part / whole) * 100;
}

console.log(percentOf(1, 4));

try {
  percentOf("1", 4);
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
25
TypeError: part and whole must be finite numbers

Use TypeError for a value of the wrong type and RangeError for one outside the allowed range. Validate at the edges of a module, where data comes from outside, and trust the types inside. In TypeScript, the signature does most of this at compile time, and runtime checks are for data from outside.

Return values

A function returns exactly one value. If the body reaches the end without a return, or a return has no expression, the result is undefined.

JavaScript
function noReturn() {
  const x = 1;
}

function earlyReturn(n) {
  if (n < 0) return "negative";
  if (n === 0) return "zero";

  return "positive";
}

console.log(noReturn(), earlyReturn(-5), earlyReturn(0), earlyReturn(9));
Text
undefined negative zero positive

Early returns keep the main path of a function flat: handle the special cases first and leave the common case at the bottom, not nested in else branches.

Returning more than one value

To return several values, return an array or an object. An object with named fields is easier for callers to use, since the order does not matter, and destructuring picks what is needed.

JavaScript
function minMax(values) {
  return { min: Math.min(...values), max: Math.max(...values) };
}

const { min, max } = minMax([4, 9, 1, 7]);

console.log(min, max);

function divide(a, b) {
  return [Math.trunc(a / b), a % b];
}

const [quotient, remainder] = divide(17, 5);

console.log(quotient, remainder);
Text
1 9
3 2

Arrays suit a short, fixed pair whose positions are conventional, as in useState. Objects suit anything else.

The line break trap

JavaScript
function broken() {
  return
  {
    ok: true
  };
}

function fixed() {
  return {
    ok: true,
  };
}

console.log(broken(), fixed());
Text
undefined { ok: true }

JavaScript inserts a semicolon after a return that is followed by a line break, so broken returns undefined and the object below it is dead code. Keep the start of the returned expression on the same line as the return. A formatter such as Prettier does this for you.

Scope, hoisting and closures

A function creates a scope, and code inside can see its own variables and those of every enclosing scope, but not the reverse. This lookup chain is called lexical scope, because it is decided by where the code is written, not by where it runs.

JavaScript
const level = "global";

function outer() {
  const level = "outer";

  function inner() {
    return level;
  }

  return inner();
}

console.log(outer(), level);
Text
outer global

inner looks for level in its own scope, finds nothing and then looks outward to outer, where it finds "outer". The global level is shadowed, and that shadowing is allowed. let and const are scoped to the block, which is any pair of braces, and var to the whole function, which is the reason modern code does not use it.

Closures

A closure is a function together with the variables from the scope where it was created. The function keeps access to them even after the outer function has returned.

JavaScript
function makeCounter(start = 0) {
  let count = start;

  return {
    increment: () => ++count,
    decrement: () => --count,
    value: () => count,
  };
}

const first = makeCounter();
const second = makeCounter(100);

first.increment();
first.increment();
second.decrement();

console.log(first.value(), second.value());
Text
2 99

Each call to makeCounter creates a separate count, and the three returned functions share the one from their call. Nothing outside can touch count except through those functions, so a closure is a way to keep private state without a class. The closures guide on this site explains how the engine keeps the scope alive, and the common traps, such as functions created in a loop.

The loop trap

JavaScript
const withVar = [];
const withLet = [];

for (var i = 0; i < 3; i++) withVar.push(() => i);
for (let j = 0; j < 3; j++) withLet.push(() => j);

console.log(withVar.map((fn) => fn()), withLet.map((fn) => fn()));
Text
[ 3, 3, 3 ] [ 0, 1, 2 ]

A var loop has one i shared by all three arrows, and by the time they run it is 3. A let loop creates a new j for each pass, and each arrow captures its own.

The value of this

Inside a regular function, this is not decided where the function is written, but how it is called. That is the single rule that explains most this bugs, and four call shapes cover everything.

JavaScript
function show() {
  return this?.label ?? "no owner";
}

const object = { label: "object", show };

console.log(object.show());
console.log(show());
console.log(show.call({ label: "call" }));
console.log(new (function () {
  this.label = "constructed";
})().label);
Text
object
no owner
call
constructed

A call through an object, object.show(), sets this to that object. A plain call, show(), leaves it undefined in strict code, and the global object in sloppy code. call, apply and bind set it by hand. And new creates a fresh object and uses it as this. A method that is pulled off its object and passed somewhere, as in setTimeout(object.show, 0), loses its owner, and the usual repairs are bind, an arrow wrapper or a class field arrow.

Arrow functions have no this, so they use the one from where they are written, which is why they are the right choice for callbacks inside methods.

JavaScript
const timer = {
  label: "timer",
  later() {
    return Promise.resolve().then(() => this.label);
  },
};

console.log(await timer.later());
Text
timer

The detailed posts on call, apply and bind and on how arrow functions treat this cover the edge cases.

Functions as values

Functions are first-class: you can store them, pass them and return them, which is what makes callbacks, higher-order functions and most of the standard library work.

Callbacks

JavaScript
function fetchUser(id, callback) {
  setTimeout(() => callback(null, { id, name: "user" + id }), 5);
}

fetchUser(7, (error, user) => {
  if (error) return console.log("failed");

  console.log("got", user);
});

console.log("requested");
Text
requested
got { id: 7, name: 'user7' }

A callback is a function you hand to another function to be called later. The log line after the call runs first, because the callback is scheduled and not executed immediately. Callbacks nested several levels deep are the reason promises exist, and the error first convention in the example is the Node.js style that older APIs use.

Higher-order functions

JavaScript
const orders = [
  { id: 1, total: 40, paid: true },
  { id: 2, total: 15, paid: false },
  { id: 3, total: 25, paid: true },
];

const paidTotal = orders
  .filter((order) => order.paid)
  .map((order) => order.total)
  .reduce((sum, total) => sum + total, 0);

console.log(paidTotal);
Text
65

filter, map and reduce take functions and own the loop. The chain reads as a description of what is wanted, and not as bookkeeping. For long chains over big lists, remember that each step makes an intermediate array.

Functions that build functions

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

function compose(...fns) {
  return (input) => fns.reduceRight((value, fn) => fn(value), input);
}

const addTax = multiplyBy(1.2);
const round = (n) => Math.round(n * 100) / 100;

console.log(compose(round, addTax)(10), multiplyBy(3)(4));
Text
12 12

multiplyBy returns a closure with the factor baked in, and compose builds a function from a list of functions, running them from right to left. These two ideas, partial application and composition, are the core of the functional style, which has its own guide.

Useful wrappers

A few small higher-order functions appear in nearly every codebase. once runs a function only the first time. memoize caches results by argument. debounce waits for calls to stop before running.

JavaScript
function memoize(fn) {
  const cache = new Map();

  return (arg) => {
    if (!cache.has(arg)) cache.set(arg, fn(arg));

    return cache.get(arg);
  };
}

let calls = 0;
const slowSquare = memoize((n) => {
  calls++;

  return n * n;
});

console.log(slowSquare(9), slowSquare(9), slowSquare(3), calls);
Text
81 81 9 2

The wrapped function ran twice, once for 9 and once for 3, and the second call with 9 came from the cache. Memoization only suits pure functions, where the same input always gives the same output, and the cache grows without a limit unless you add one.

Pure functions and side effects

A pure function returns a value that depends only on its arguments, and changes nothing outside itself. An impure function reads or changes something else: a variable in an outer scope, the clock, the file system, the network, the input it was given.

JavaScript
const items = [3, 1, 2];

function impureSort(list) {
  return list.sort();
}

function pureSort(list) {
  return list.toSorted();
}

console.log(pureSort(items), items);
console.log(impureSort(items), items);
Text
[ 1, 2, 3 ] [ 3, 1, 2 ]
[ 1, 2, 3 ] [ 1, 2, 3 ]

The pure version leaves the caller's array alone. The impure one rearranged it, and every other reference to the array saw the change. Pure functions are easy to test, since there is nothing to set up, easy to cache and easy to reason about. A program still needs side effects, since printing and saving are the point, so the usual design keeps the core logic pure and pushes the effects to the edges.

Recursion

A function that calls itself solves a problem by reducing it to a smaller one of the same shape. Every recursive function needs a base case that stops it and a recursive case that moves toward the base.

JavaScript
function flatten(value) {
  if (!Array.isArray(value)) return [value];

  return value.flatMap(flatten);
}

function sumTo(n) {
  return n === 0 ? 0 : n + sumTo(n - 1);
}

console.log(flatten([1, [2, [3, [4]]]]), sumTo(100));
Text
[ 1, 2, 3, 4 ] 5050

Recursion fits trees and nested data: a directory, a parsed document, a menu. It does not fit loops that run as many times as there are items in a long list, because each call uses stack space, and the engine does not optimize tail calls, so a deep enough input ends with RangeError: Maximum call stack size exceeded. For those, write a loop, or keep your own stack in an array.

Asynchronous functions

JavaScript runs one piece of code at a time, and long operations such as network requests and timers are started and finished later, through callbacks, promises and async functions.

JavaScript
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function loadAll() {
  const sequential = [await wait(10, "a"), await wait(10, "b")];
  const parallel = await Promise.all([wait(10, "c"), wait(10, "d")]);

  return [...sequential, ...parallel];
}

console.log(await loadAll());
Text
[ 'a', 'b', 'c', 'd' ]

An async function always returns a promise, and await pauses that function, not the whole program, until a promise settles. The first pair waited one after the other, which takes the sum of the times, and the second started both at once with Promise.all, which takes the longest of them. When the operations do not depend on each other, start them together.

Handling errors

JavaScript
async function risky(shouldFail) {
  if (shouldFail) throw new Error("request failed");

  return "ok";
}

async function main() {
  try {
    console.log(await risky(false));
    console.log(await risky(true));
  } catch (error) {
    console.log("caught:", error.message);
  } finally {
    console.log("cleanup");
  }
}

await main();
Text
ok
caught: request failed
cleanup

A thrown error inside an async function becomes a rejected promise, and await turns it back into a thrown error that try and catch can handle. A rejected promise that nobody awaits or catches becomes an unhandled rejection, which Node.js turns into a crash by default, so always await or attach a handler.

Function objects

A function is an object, so it has properties and methods.

JavaScript
function sample(a, b = 2, ...rest) {}

console.log(sample.name, sample.length, typeof sample.call, sample instanceof Object);
console.log(sample.toString());
Text
sample 1 function true
function sample(a, b = 2, ...rest) {}

name is the function's name, length is the number of parameters before the first default or rest, and toString returns the source text. You can attach your own properties, but the cleaner way to carry state is a closure or a class. The Function constructor, new Function("a", "return a"), builds a function from a string, and like eval, it should be avoided: it defeats tooling, and it is a security risk with untrusted text.

Dispatch tables and the strategy pattern

A common use of functions as values is to replace a long if or switch chain with a lookup. The object maps a key to a function, and the code that chooses behavior becomes one property read.

JavaScript
const formatters = {
  json: (data) => JSON.stringify(data),
  csv: (data) => Object.values(data).join(","),
  text: (data) => Object.entries(data).map(([key, value]) => `${key}=${value}`).join("; "),
};

function render(data, format = "json") {
  const formatter = formatters[format];

  if (!formatter) throw new RangeError(`unknown format: ${format}`);

  return formatter(data);
}

const row = { id: 7, name: "Ana" };

console.log(render(row), render(row, "csv"), render(row, "text"));
Text
{"id":7,"name":"Ana"} 7,Ana id=7; name=Ana

Adding a format means adding one entry, and the render function never changes. This is the strategy pattern from object-oriented design, without the class hierarchy, and it is the reason first-class functions often replace interfaces and subclasses in JavaScript. Two cautions apply. A lookup on a plain object also finds inherited names such as toString, so use Object.hasOwn(formatters, format) or a Map when the key comes from user input. And keep the table next to the function that uses it, or export it deliberately, since a shared mutable table is global state in disguise.

Functions and objects: where behavior should live

JavaScript lets you put behavior in a method on an object or in a standalone function that takes the object. Both work, and the choice affects how code is tested, reused and tree-shaken.

JavaScript
// as a method
class Cart {
  constructor(items) {
    this.items = items;
  }

  total() {
    return this.items.reduce((sum, item) => sum + item.price * item.qty, 0);
  }
}

// as a standalone function over plain data
const cartTotal = (items) => items.reduce((sum, item) => sum + item.price * item.qty, 0);

const items = [
  { price: 5, qty: 2 },
  { price: 3, qty: 4 },
];

console.log(new Cart(items).total(), cartTotal(items));
Text
22 22

A method keeps the behavior with the data and lets subclasses override it. A standalone function works on any object with the right shape, including plain objects from JSON, needs no class and is easier to import one at a time, which helps bundlers remove what you do not use. For data that moves across a network or into storage, plain objects and functions are simpler, because a class instance loses its methods when it is serialized. For long-lived objects with identity and several operations that share private state, a class fits. Many codebases use both: classes for the few stateful services, and functions for the data transformations.

Writing functions that last

The language gives you freedom, and the habits below are what keep a large codebase understandable.

Do one thing and name it. A function whose name needs "and" in it is two functions. A good name is a verb phrase that says what the call does or returns, such as parseDate, isExpired or buildQuery. Names that start with is, has or can should return a boolean.

Keep the argument list short. Up to three positional parameters is fine. More than that, or several booleans, and an options object is clearer, since render(true, false, true) says nothing at the call site.

Avoid boolean flag parameters. A function that does one thing when a flag is true and another when it is false is two functions. Split it, and give each a name.

Return early, nest less. Handle invalid input at the top and let the main path run without indentation.

Do not mutate your inputs. Return a new value, or say clearly in the name and documentation that the function changes its argument, as sort does.

Make failure obvious. Throw errors for conditions the caller cannot reasonably ignore, and return a value, such as undefined or an empty array, for ordinary absence. Do not mix the two in one function without documenting which cases do which.

Prefer pure functions for logic. Parsing, formatting, validation and calculation should take values and return values. Reading files and calling APIs belong in a thin layer around them.

JavaScript
// hard to test: reads the clock and a global
let discountRate = 0.1;

function priceNow(base) {
  return new Date().getHours() < 12 ? base * (1 - discountRate) : base;
}

// easy to test: everything it needs is an argument
function priceAt(base, hour, rate) {
  return hour < 12 ? base * (1 - rate) : base;
}

console.log(priceAt(100, 9, 0.1), priceAt(100, 15, 0.1));
Text
90 100

The second form can be tested with any hour you like, and priceNow is the thin wrapper that supplies the clock.

When a function actually runs

A function call runs to completion before anything else gets a turn. That rule, run to completion, is why JavaScript code can mutate shared variables without locks, and it is also why a long loop freezes a page or blocks a server. Work that is scheduled, such as a timer callback or a promise handler, waits in a queue until the current call finishes and the stack is empty.

JavaScript
console.log("1 start");

setTimeout(() => console.log("4 timeout"), 0);

Promise.resolve().then(() => console.log("3 promise"));

console.log("2 end");
Text
1 start
2 end
3 promise
4 timeout

The two synchronous lines ran first, in order. The promise handler ran next, since promise callbacks go in a microtask queue that is emptied right after the current call. The timer callback ran last, even though its delay was zero, because timers go in a separate queue that is serviced after the microtasks. Knowing the order matters when you reason about await: everything after an await in an async function runs as a microtask continuation, and never in the middle of the synchronous code that called it.

Currying and partial application

Partial application fixes some of a function's arguments and returns a function that takes the rest. Currying turns a function of several parameters into a chain of functions that each take one.

JavaScript
const add = (a, b, c) => a + b + c;
const curriedAdd = (a) => (b) => (c) => a + b + c;

const addTen = (b, c) => add(10, b, c);
const addTenAndFive = curriedAdd(10)(5);

console.log(addTen(1, 2), addTenAndFive(1), curriedAdd(1)(2)(3));
Text
13 16 6

addTen is partial application written by hand, and curriedAdd is the curried form. Both are closures over the arguments that were given first. The practical use is configuration: const log = prefix => message => console.log(prefix + message) gives you a family of loggers from one function. Currying is more common in languages with a strong functional tradition. In JavaScript, an arrow wrapper or bind is usually the most readable way to fix some arguments, and curried helpers shine mostly inside map and filter pipelines.

Debounce and throttle

Two wrappers appear in almost every front-end project. A debounced function waits until calls stop for a given time before it runs, which is right for a search box that should query after the user stops typing. A throttled function runs at most once in a given time, which suits scroll and resize handlers.

JavaScript
function debounce(fn, delay) {
  let timer;

  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

const search = debounce((term) => console.log("searching for", term), 20);

search("j");
search("js");
search("jsh");

await new Promise((resolve) => setTimeout(resolve, 60));
Text
searching for jsh

Three calls arrived within the delay, and only the last one ran. The wrapper keeps the timer id in a closure, so each wrapped function has its own timer. A production version also returns a way to cancel the pending call and handles this, and libraries such as Lodash provide those. The point here is that both wrappers are a dozen lines of closure and timer, and they show why first-class functions are so useful.

Functions that keep state

There are three ways to give a function memory, and each fits a different size of problem.

JavaScript
// 1. A closure: private state, one concern
function createIdGenerator(prefix) {
  let next = 1;

  return () => prefix + next++;
}

// 2. An object with methods: several operations on shared state
const stack = {
  items: [],
  push(item) {
    this.items.push(item);

    return this;
  },
  pop() {
    return this.items.pop();
  },
};

// 3. A class: many instances with the same behavior
class Queue {
  #items = [];

  enqueue(item) {
    this.#items.push(item);
  }

  dequeue() {
    return this.#items.shift();
  }

  get size() {
    return this.#items.length;
  }
}

const nextId = createIdGenerator("user-");
const queue = new Queue();

queue.enqueue("a");
queue.enqueue("b");
stack.push(1).push(2);

console.log(nextId(), nextId(), stack.pop(), queue.dequeue(), queue.size);
Text
user-1 user-2 2 a 1

A closure is the lightest: one function, one piece of private state. An object literal groups related operations when you need exactly one of them. A class with private fields is the right choice when you create many instances, or when other code needs to check what something is with instanceof. Start with the lightest form that works, and move up when the code asks for it.

Result objects and error design

A function can signal failure by throwing, by returning a special value or by returning a result object. Each fits different situations, and mixing them without a pattern is how error handling becomes hard to follow.

JavaScript
function parsePort(text) {
  const port = Number(text);

  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    return { ok: false, error: `invalid port: ${text}` };
  }

  return { ok: true, value: port };
}

for (const input of ["8080", "http", "70000"]) {
  const result = parsePort(input);

  console.log(result.ok ? "port " + result.value : result.error);
}
Text
port 8080
invalid port: http
invalid port: 70000

Throw when the failure is exceptional and the caller probably cannot continue, such as a missing required file or a violated invariant. Return a result object, or undefined or null, when failure is an ordinary outcome that the caller will check, such as parsing user input or a lookup that may find nothing. Whatever you choose, document it, and use the same style for similar functions, so that callers can guess correctly.

Types for functions

In TypeScript, a function's parameters and return value get types, and the compiler checks every call.

TypeScript
function area(width: number, height = width): number {
  return width * height;
}

type Predicate<T> = (value: T) => boolean;

function count<T>(items: T[], test: Predicate<T>): number {
  return items.filter(test).length;
}

console.log(area(3), count([1, 2, 3, 4], (n) => n % 2 === 0));
Text
9 2

The types are erased when the code compiles, so the output is the same as the plain JavaScript version. They catch the wrong-type and missing-argument mistakes at compile time, which is the main reason to add them. For plain JavaScript, a JSDoc comment with @param and @returns gives the same hints to editors, and tsc --checkJs can verify them.

Modules and functions

In an ES module, functions are exported and imported by name, and everything else in the file stays private.

JavaScript
// math.mjs
export function clamp(n, min, max) {
  return Math.min(Math.max(n, min), max);
}

function helper() {
  return "not exported";
}

export default function describe(n) {
  return n < 0 ? "negative" : "non-negative";
}
JavaScript
// main.mjs
import describe, { clamp } from "./math.mjs";

console.log(clamp(15, 0, 10), describe(-1));
Text
10 negative

A named export is imported with braces and must keep its name, which helps refactoring and autocompletion. A default export can be imported under any name. Most style guides prefer named exports for functions, so that a search for a function finds every use. Keep modules small, with a focused set of functions, and put the pure ones in their own files, so that tests and other modules can import them without side effects.

From callbacks to promises

Older Node.js APIs take a callback with the error as the first argument. Turning one into a function that returns a promise is a small wrapper, and the standard library ships a helper for it, util.promisify.

JavaScript
import { promisify } from "node:util";

function legacyRead(name, callback) {
  setTimeout(() => {
    if (name === "missing") return callback(new Error("not found: " + name));

    callback(null, "contents of " + name);
  }, 5);
}

const read = promisify(legacyRead);

console.log(await read("notes.txt"));

try {
  await read("missing");
} catch (error) {
  console.log(error.message);
}
Text
contents of notes.txt
not found: missing

promisify expects the callback to be the last parameter and to follow the error-first convention, and it returns a function that resolves with the second argument or rejects with the first. Many modules also ship a promise version of their API, such as node:fs/promises, which you should prefer to wrapping the callback form yourself. Writing the wrapper by hand is still a good exercise in how a function can return a promise: new Promise((resolve, reject) => { ... }) with resolve and reject called from inside the callback.

Overloading by inspecting arguments

JavaScript has no function overloading, since a name refers to one function. When one function must accept several shapes of input, it inspects what it received.

JavaScript
function formatDate(input) {
  if (input instanceof Date) return input.toISOString().slice(0, 10);
  if (typeof input === "number") return formatDate(new Date(input));
  if (typeof input === "string") return formatDate(new Date(input + "T00:00:00Z"));

  throw new TypeError("expected a Date, a timestamp or an ISO date string");
}

console.log(formatDate(new Date(0)), formatDate(86400000), formatDate("2026-03-01"));
Text
1970-01-01 1970-01-02 2026-03-01

Each branch normalizes its input to a Date and calls the function again, so the real work is written once. This style is fine for a small number of shapes. When the shapes diverge in behavior, separate functions with clear names, such as parseDate and formatTimestamp, are easier to read and to type, and TypeScript overload signatures can describe the different shapes without changing the runtime code.

Method chaining

A method that returns this, or a new object of the same kind, allows calls to be chained, as in query.where(a).orderBy(b).limit(10). Arrays do it by returning new arrays from map and filter, and builders do it by returning the builder.

JavaScript
class Query {
  #parts = [];

  from(table) {
    this.#parts.push("FROM " + table);

    return this;
  }

  where(condition) {
    this.#parts.push("WHERE " + condition);

    return this;
  }

  limit(count) {
    this.#parts.push("LIMIT " + count);

    return this;
  }

  toString() {
    return "SELECT * " + this.#parts.join(" ");
  }
}

console.log(String(new Query().from("users").where("active = 1").limit(5)));
Text
SELECT * FROM users WHERE active = 1 LIMIT 5

Chaining reads well when each step is a small, named change, and badly when the chain is long and mixes unrelated operations. It also hides the difference between a method that mutates the builder and one that returns a new object, so document which it is. The example above mutates and returns this, and an immutable builder would return a fresh Query from each call.

What a function costs

Functions are cheap, and calling one is not something to avoid for speed. The cost worth knowing about is memory: a closure keeps its whole scope alive for as long as the closure is reachable, so a small callback that references a large object keeps that object in memory. Creating a function inside a hot loop allocates a function object each pass, and engines often handle that well, but if profiling shows it as a problem, move the function out of the loop. A recursive call costs stack space, so depth is the limit. We do not quote timings, since they depend on the engine, the version and the code. If a function is slow, profile with the Node.js --cpu-prof flag or the browser's performance panel, and fix the part that the profile shows, not the part that looks suspicious.

A checklist for reading an unfamiliar function

When you open a function that you did not write, work through the same questions, in order. What are the parameters, and which ones have defaults? What does each return path produce, including the implicit undefined? Does it read or change anything outside itself: a module variable, this, a global, the file system, the clock? Is it asynchronous, and does it return a promise that callers must await? Can it throw, and under what conditions? Does it use this or arguments, which tells you how it must be called? Does any inner function capture a variable that changes? A minute spent on these questions finds most of the surprises that cause bugs, and writing a function so that the answers are obvious is the aim of the design rules above.

Testing and debugging functions

A pure function needs only a table of inputs and expected outputs, which is why they are the cheapest code to test. With the built-in Node.js test runner, a test is a function too.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

function clamp(n, min, max) {
  return Math.min(Math.max(n, min), max);
}

test("clamp keeps a value inside the range", () => {
  assert.equal(clamp(5, 0, 10), 5);
  assert.equal(clamp(-3, 0, 10), 0);
  assert.equal(clamp(99, 0, 10), 10);
});
Text
āœ” clamp keeps a value inside the range (0.9ms)

The run prints one line per test, and the time in brackets differs on your machine, followed by a summary of passed and failed counts. To debug a function, log its arguments at the top and its result before each return, use debugger or an editor breakpoint to step through, and read the stack trace from the top for the first line in your own code. When a function behaves differently when called from two places, the cause is nearly always this, a shared mutable value or a closure over a changing variable.

Common mistakes

Calling a function without parentheses, greet where you meant greet(), gives you the function and not its result. Passing fn() where you meant fn calls it immediately and hands over the result, as in setTimeout(run(), 100). Using an arrow function as an object method and reading this. Forgetting return in a braced arrow, so that map produces an array of undefined. Mutating a parameter that is an object or an array. Using async callbacks with forEach, which does not wait for them. Putting a default value that depends on a later parameter. Relying on hoisting for const functions. And catching an error and ignoring it, which turns a visible failure into a silent one.

A quick reference

You wantUse
A top-level helpera function declaration
A callback or a short functionan arrow function
An object or class methodthe method shorthand
A constructora class
A variable number of argumentsa rest parameter
Many optional settingsone destructured options object
Private statea closure or a #private field
Fixed this or argumentsbind, or an arrow wrapper
Lazy or infinite sequencesa generator
Waiting for I/Oan async function
Repeated pure workmemoization

Learning path

If you are learning functions in order, work through them in this sequence, and write a small program at each step. First, declarations and arrows, with parameters, defaults and return values, until you can write a helper without looking anything up. Second, scope and closures, by building a counter and a function that remembers its settings. Third, this, by writing a small object with methods and passing one of them to setTimeout, then fixing it three ways. Fourth, higher-order functions, by rewriting a loop as map, filter and reduce. Fifth, asynchronous functions, by fetching two things in sequence and then in parallel. Sixth, testing, by covering each function with a table of inputs. Each step is a few hours of practice, and the order matters, because every later step uses the earlier ones. The related guides on closures, generators and functional programming then deepen the parts where functions meet other ideas.

Where this guide stops

Functions touch everything else in the language, so some subjects need their own treatment. Closures, generators and iterators, and functional programming each have a guide here, with the details that this overview only sketches. TypeScript adds function types, overloads and generics, which change how you write signatures but not how functions run. And performance advice about functions, such as inlining and the cost of closures, depends on the engine and the data, so measure in your own application and treat any number from an unrelated benchmark with suspicion.

Taggednode 24
Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.