Object.assign Skips null And undefined Sources
Object.assign skips null and undefined sources, overwrites keys layer by layer, and mutates only its first argument, so pass {} first to keep defaults intact.
Code
const defaults = { retries: 2, timeout: 5000, label: 'job' };
// null and undefined sources are skipped; real layers overwrite key by key.
const envLayer = null; // e.g. no CLI overrides found for this run
const userLayer = { retries: 5, label: 'sync-job' };
const merged = Object.assign({}, defaults, envLayer, userLayer);
console.log(JSON.stringify(merged));
// Assigning undefined explicitly still overwrites: defaults do not "win".
const withBlank = Object.assign({}, defaults, { label: undefined });
console.log('label present but undefined:', withBlank.label);
// The first argument is mutated in place; pass {} to keep defaults untouched.
console.log('defaults intact:', JSON.stringify(defaults));Output
Captured from a sandboxed run of this snippet in the build pipeline.
{"retries":5,"timeout":5000,"label":"sync-job"}
label present but undefined: undefined
defaults intact: {"retries":2,"timeout":5000,"label":"job"}What happens on each run — Object.assign Skips null And undefined Sources
The file works entirely over top-level bindings: defaults, envLayer, userLayer, merged.
Module-level object literal, fixed keys: retries, timeout, label.
Points of care
- The package manager never enters the picture for this snippet.
Putting it to use
Output lines are prefixed (label present but undefined:, defaults intact:), so the reader can match output lines to their steps.
Core lines
const withBlank = Object.assign({}, defaults, { label: undefined });
const envLayer = null; // e.g. no CLI overrides found for this run
const userLayer = { retries: 5, label: 'sync-job' };
const merged = Object.assign({}, defaults, envLayer, userLayer);
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `defaults`, `envLayer`, `userLayer`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.