Optional spreading [?...ArrayOrNullish]
{?...ObjectOrNullish}
. Noop when spreading value is nullish
. Intuitive addition to javascript, inspired by optional chaining and Nullish coalescing operator
Spreading is great, it contributes towards "declerativity" of the language and reduces verbosity, but in case value being spread is nullish
, we either have to give up on this feature or sacrifice verbosity and performance for declarativity.
Consider following code pattern that naturally appears in configuartion management
function getConfig(customConfig) {
return {
plugins: [
BasePlugin(),
...customConfig?.plugins
],
}
}
As you may have hoticed, code above uses optional chaining in case customConfig
is "nullish", so we are safe there.
But what happens if plugins array is not defined on customConfig
, our functions will throw, and to fix it we need an extra check like:
...(customConfig?.plugins ?? [])
expression above makes use of nullish coalescing operator, to return an empty array to spread(...
) operator, so our code is safe and still declerative but verbosity of code has increased a bit and creation of empty array makes performance nerds like myself cringe.
It would be so much nicer if we could do something like:
?...customConfig?.plugins
which is much safer, more performant and much cleaner approach.
Needless to say that it is very intuitive thanks to optional chaining and nullish coalescing opertator
Thanks!
Object spread already handles
null
ish values:This is done in CopyDataProperties, which is called from PropertyDefinitionEvaluation.