Spread Null Undefined Asymmetry
Object spread skips null and undefined sources while array spread throws TypeError, so config merging needs no guard but list concat does.
Code
// The asymmetry: object spread silently skips null and undefined sources,
// while array spread throws on them
console.log('object spread of null:', { retries: 3, ...null, ...undefined });
try {
const items = [...null];
console.log('array spread ok:', items);
} catch (err) {
console.log('array spread of null threw:', err.constructor.name);
}
// config merging therefore needs no null guard for object layers
const base = { host: 'localhost', port: 8080, retries: 3 };
const override = null; // absent layer
const merged = { ...base, ...override };
console.log('merged with null override:', merged);
console.log('layered:', { ...base, ...undefined, retries: 1 });
// arrays and iterables DO need a nullish guard before spreading
function concatAll(lists) {
return lists.reduce((acc, list) => acc.concat(list ?? []), []);
}
console.log('concat with nullish entry:', concatAll([[1, 2], null, [3]]));
// Array.from on a nullish value throws too, unless you coalesce first
console.log('Array.from(null ?? []):', Array.from(null ?? []));
try {
Array.from(null);
} catch (err) {
console.log('Array.from(null) threw:', err.constructor.name);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
object spread of null: { retries: 3 }
array spread of null threw: TypeError
merged with null override: { host: 'localhost', port: 8080, retries: 3 }
layered: { host: 'localhost', port: 8080, retries: 1 }
concat with nullish entry: [ 1, 2, 3 ]
Array.from(null ?? []): []
Array.from(null) threw: TypeErrorHow it works
Spread Null Undefined Asymmetry comes down to the function concatAll.
Using it
Entry signature: function concatAll(lists)
The run emits 8 labeled sections — object spread of null:, array spread ok:, array spread of null threw:, merged with null override:, layered:, concat with nullish entry:, Array.from(null ?? []):, Array.from(null) threw: — one per step.
Key statements
return lists.reduce((acc, list) => acc.concat(list ?? []), []);
Interactive Tools for This Topic
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `concatAll` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.