Skip to content
jshacks.dev
Functions

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.

1 min read
Summarize in AI

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.

JavaScript
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 }));
Text
ada-2026-50
ada-2030-7

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

Also inSecurity
Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read
Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 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.