Lazy Initialization Patterns
Lazy initialization delays creating a value until it is first needed. See memoized getters, async lazy values, ??= and self-replacing properties in JavaScript.

Lazy initialization means creating a value the first time it is used, not when the program starts. It saves work for values that may never be needed, speeds up startup and lets expensive setup wait until a request actually asks for it. The patterns are small, but several have sharp edges: a value that is undefined legitimately, an async setup that two callers start at once, a cached failure that never retries. This post covers the main forms on Node.js 24 with their outputs: ??=, memoized functions, getters that replace themselves, async lazy values and lazy modules, and explains how to choose and test them.
Why be lazy
Eager setup is simple: build everything at startup and use it anywhere. The cost shows up in three places. Startup slows down as the number of things to build grows, which matters for command-line tools and serverless functions where a process lives for milliseconds. Memory is held for values that are never used. And a failure in setup for something rarely used stops the whole program from starting.
Laziness moves the cost to the first use, and sometimes it never arrives. The trade is that the first caller pays, and the code is a little more complex because it must track whether the value exists yet.
The simplest form: ??=
The logical nullish assignment operator assigns only if the left side is null or undefined, which is exactly "initialize if missing".
let calls = 0;
const cache = {};
function getSettings() {
cache.settings ??= (calls += 1, { theme: "dark", loadedAt: calls });
return cache.settings;
}
console.log(getSettings());
console.log(getSettings());
console.log(calls);{ theme: 'dark', loadedAt: 1 }
{ theme: 'dark', loadedAt: 1 }
1The initializer ran once, and both calls got the same object. The comma expression is only there to count calls for the demonstration; in real code the right side would be the construction. ??= treats only null and undefined as missing, so a stored 0 or empty string counts as initialized. If a legitimate value is undefined or null, this pattern re-runs the initializer every time, which leads to the next form.
Tracking initialization explicitly
When undefined or null can be a valid result, store a separate flag, or wrap the value.
function lazy(factory) {
let initialized = false;
let value;
return () => {
if (!initialized) {
value = factory();
initialized = true;
}
return value;
};
}
let runs = 0;
const getNothing = lazy(() => {
runs += 1;
return undefined;
});
getNothing();
getNothing();
console.log(runs);1The initialized flag distinguishes "not yet computed" from "computed as undefined". This lazy helper is also the base of memoization for functions with no arguments, and it is worth having in a utilities file.
Memoizing a function with arguments
A function with parameters needs a cache keyed by the arguments. A Map is the right structure, because it takes any value as a key and has no inherited properties.
function memoize(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) cache.set(arg, fn(arg));
return cache.get(arg);
};
}
let computations = 0;
const square = memoize((n) => {
computations += 1;
return n * n;
});
console.log(square(4), square(4), square(5));
console.log(computations);16 16 25
2Three calls, two real computations: the repeated square(4) came from the cache. Using cache.has and not checking for undefined means a function that returns undefined is still cached. Memoization holds results forever, so a function called with many different arguments grows the cache without bound. For keys that are objects, use a WeakMap, which lets the garbage collector remove an entry when its key is no longer used elsewhere. For bounded caches, use a least-recently-used structure.
Self-replacing getters
A getter can compute a value once and then replace itself with a plain data property, so later reads cost nothing and do not run the getter logic again.
class Report {
constructor(rows) {
this.rows = rows;
}
get summary() {
console.log("computing summary");
const value = { count: this.rows.length, total: this.rows.reduce((a, b) => a + b, 0) };
Object.defineProperty(this, "summary", { value, enumerable: true });
return value;
}
}
const report = new Report([10, 20, 30]);
console.log(report.summary);
console.log(report.summary);
console.log(Object.keys(report));computing summary
{ count: 3, total: 60 }
{ count: 3, total: 60 }
[ 'rows', 'summary' ]The first read ran the getter and printed the message. Object.defineProperty on the instance created an own property named summary, which shadows the prototype's getter, so the second read found a plain value and did not recompute. The getter is defined on the prototype, so each instance replaces it independently. The Object.keys output shows summary became an own, enumerable property after first use. If you prefer it to stay hidden from enumeration, omit enumerable: true.
A simpler variant uses a private field and the ??= operator inside the getter, which keeps the property a getter forever and avoids defineProperty.
class Report {
#summary;
constructor(rows) {
this.rows = rows;
}
get summary() {
return (this.#summary ??= { count: this.rows.length });
}
}
const r = new Report([1, 2, 3]);
console.log(r.summary === r.summary);trueBoth reads return the same object. This form is easier to read, and it fails safely if the computation can return undefined, which would re-run each time.
Lazy async values
Asynchronous setup, such as opening a database connection, adds a hazard: two callers can arrive before the first finishes, and both start their own setup. Store the promise, not the result, so the second caller shares the first one's work.
let connections = 0;
let connectionPromise;
function getConnection() {
connectionPromise ??= (async () => {
connections += 1;
await new Promise((resolve) => setTimeout(resolve, 10));
return { id: connections };
})();
return connectionPromise;
}
const [a, b] = await Promise.all([getConnection(), getConnection()]);
console.log(a.id, b.id, a === b, connections);1 1 true 1Both callers awaited the same promise, so only one connection was opened. Had the code stored the resolved value instead, a second caller arriving during the wait would have started a second connection, since the value was not set yet.
Do not cache failures forever
The promise-caching version has a flaw: if the setup rejects, the rejected promise stays cached, and every later call fails with the same error, even after the cause has gone. Clear the cache on failure so the next call retries.
let attempts = 0;
let pending;
function getResource() {
pending ??= (async () => {
attempts += 1;
if (attempts === 1) throw new Error("not ready");
return `ready after ${attempts} attempts`;
})().catch((err) => {
pending = undefined;
throw err;
});
return pending;
}
try {
await getResource();
} catch (err) {
console.log(err.message);
}
console.log(await getResource());not ready
ready after 2 attemptsThe catch handler resets pending before re-throwing, so the second call starts a fresh attempt and succeeds. Whether to retry on every call, or to back off, is a design choice, and a circuit breaker or retry helper may sit in front.
Lazy modules
Loading code is initialization too. A dynamic import() loads a module on first use, which keeps rarely used dependencies out of startup.
let utilModule;
async function stripColors(text) {
utilModule ??= await import("node:util");
return utilModule.stripVTControlCharacters(text);
}
console.log(await stripColors("\u001b[31mred\u001b[0m"));redThis example uses node:util so that it needs no install, and the pattern is the same for a heavy third-party package: import it inside the function that needs it, and cache the module. Node.js caches modules itself, so repeated import() calls are cheap, and the ??= is only an optimization. A tool with many subcommands benefits the most, since running one command loads only the code it needs.
Lazy sequences
Generators are lazy by nature: the work for each item happens when the consumer asks for it. A lazy sequence is the right shape when the whole list is large or expensive and you may use only part.
let evaluated = 0;
function* expensiveItems() {
for (let i = 1; i <= 1000; i++) {
evaluated += 1;
yield i * i;
}
}
const firstThree = expensiveItems().take(3).toArray();
console.log(firstThree, evaluated);[ 1, 4, 9 ] 3Only three items were computed out of a thousand. Building the full array first would have computed all of them. Iterator helpers such as take are available in Node.js 22 and later.
Pitfalls
Hidden cost on the hot path. The first request pays for initialization. If that request is a user waiting, you have moved latency from startup to the worst moment. For values you will certainly need, initialize early, in the background, and keep laziness for the optional ones.
Thread-like races with async. Always cache the promise, as shown, and never check and set across an await.
Stale values. A lazily built value is built from the state at that moment. If the inputs change later, the cached value is out of date. Decide whether it needs invalidation, such as a reset function, a time-to-live or a version key.
Testing order. A module-level lazy value keeps its state between tests, so a test that runs second sees what the first created. Expose a reset for tests, or build lazy values inside a factory.
Errors at a distance. Eager setup fails at startup, when the operator is watching. Lazy setup fails on the first use, possibly hours later. For configuration that must be valid, validate eagerly and initialize heavy objects lazily.
Testing
Test that the initializer runs once, that failures can retry and that concurrent callers share work.
import assert from "node:assert/strict";
import { test } from "node:test";
test("lazy runs the factory once and shares the result", () => {
let runs = 0;
const get = lazy(() => {
runs += 1;
return { id: 1 };
});
assert.equal(runs, 0);
assert.equal(get(), get());
assert.equal(runs, 1);
});✔ lazy runs the factory once and shares the result (0.8ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0The first assertion checks the laziness itself: nothing ran before the first call.


