Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

TLDR;

Optional spreading [?...ArrayOrNullish] {?...ObjectOrNullish}. Noop when spreading value is nullish. Intuitive addition to javascript, inspired by optional chaining and Nullish coalescing operator

Problem

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.

Proposed solution

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!

@ExE-Boss

This comment has been minimized.

Copy link

@ExE-Boss ExE-Boss commented Jun 4, 2020

Object spread already handles nullish values:

{...undefined};
// returns {}

{...null};
// returns {}

This is done in CopyDataProperties, which is called from PropertyDefinitionEvaluation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.