Use default parameters for dependency injection
Use default parameters for dependency injection in JavaScript, passing real clients by default and fakes in tests. Works in Node.js 24, no framework.
You do not need a container to inject dependencies. A default parameter gives production code the real thing and lets a test pass a fake.
const realClock = { now: () => new Date('2026-01-01T00:00:00Z') };
const makeToken = (user, { clock = realClock, random = Math.random } = {}) =>
`${user}-${clock.now().getUTCFullYear()}-${Math.floor(random() * 100)}`;
console.log(makeToken('ada', { random: () => 0.5 }));
console.log(makeToken('ada', { clock: { now: () => new Date('2030-06-01T00:00:00Z') }, random: () => 0.07 }));ada-2026-50
ada-2030-7The first call keeps the default clock, which is fixed in this example, and replaces only random. The second call replaces both, so the year and the number are exact in each. The second argument is an object with defaults, so callers name only what they replace. See default parameters.
Never use it for secrets: tokens that guard anything need crypto.randomUUID or crypto.randomBytes, and Math.random is not safe for that. Keep the injected object small, or the signature becomes hard to read.