Spreading nullish values
To throw or not to throw?
// Array spread�const mergedArray = [...array1, ...array2];�// → throws if e.g. `array2` is `null` or `undefined`��// Object spread�const mergedObject = { ...object1, ...object2 };�// → ignores e.g. `object2` if it’s `null` or `undefined`
Option 1
Option 2
Option 3
Option 4
Options: recap
Object spread rationale
null | undefined | Point3D
Not very common type:
{} | Point3D
?Point3D
Not very common type:
{} | Point3D
{ ...obj || {} }
We don’t recommend obj || {} as a pattern elsewhere.
obj ? { foo: obj.foo, bar: obj.bar, baz: value } : { baz: value }
{ ...obj, baz: someValue }
{ ...(obj || {}), baz: someValue }
arr ? [arr[0], arr[1], arr[2], value] : []
[ ...arr, value ]
[ ...(arr || []), value ]
{ ...obj, foo: {...obj?.foo, bar: 1 }}
{ ...obj || {}, foo: {...obj?.foo || {}, bar: 1 }}