defaults()
defaults<
T>(object, ...sources):T
Assigns source properties to destination only where destination is undefined.
๐ Why is this a Hidden Gem?
Safely applies default values only where properties are undefined.
Only undefined values are replaced. null values are preserved.
Type Parametersโ
T: T extends Record<string, unknown>โ
The type of the destination object.
Parametersโ
object: Tโ
The destination object.
sources: ...Record<string, unknown>[]โ
The source objects.
Returns: Tโ
A new object with defaults applied (does not mutate original).
Sinceโ
2.0.0
Noteโ
Inherited properties (e.g., from Object.prototype) are not considered undefined.
Performanceโ
O(nรm) where n = number of sources, m = average keys per source
Also known asโ
assign (Radashi) ยท defaults (Lodash, es-toolkit) ยท mergeRight (Ramda) ยท โ (Remeda, Effect, Modern Dash, Antfu)
Exampleโ
const target = { a: 1, b: undefined, c: 3 };
const source = { b: 2, c: 4, d: 5 };
defaults(target, source);
// => { a: 1, b: 2, c: 3, d: 5 }
// Original is not mutated
target.b; // => undefined (unchanged)
// null is preserved (not undefined)
defaults({ city: null }, { city: 'Paris' });
// => { city: null }
// Multiple sources (first wins)
defaults({ a: 1 }, { b: 2 }, { b: 3, c: 4 });
// => { a: 1, b: 2, c: 4 }
How it works?โ
Fills in undefined properties with values from source objects.
Only undefined values are replaced โ null is preserved.
null vs undefinedโ
null is preserved because it's a deliberate value, not absence.
Multiple Sourcesโ
First source wins for each key.
Use Casesโ
Initialize configuration options ๐โ
Apply default settings to a user-provided config object without overwriting explicit nulls. Perfect for library initialization or function parameters.
const config = defaults(userOptions, {
timeout: 5000,
retries: 3,
verbose: true
});
Preserve explicit nullsโ
Ensure that null values provided by the user are respected (not treated as missing).
Critical for APIs where null has a specific semantic meaning (e.g., "disable feature").
const options = defaults({ cache: null }, { cache: true });
// options.cache is null (user disabled it)
Combine multiple sourcesโ
Layer multiple default objects to build a final configuration. Useful for cascading settings (Global -> Project -> User).
const final = defaults(userOpts, projectDefaults, globalDefaults);