Skip to content

Instantly share code, notes, and snippets.

@askbeka
Last active October 22, 2020 10:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save askbeka/8bb17508ec250a789ea9bff683a50e38 to your computer and use it in GitHub Desktop.
Save askbeka/8bb17508ec250a789ea9bff683a50e38 to your computer and use it in GitHub Desktop.

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
Copy link

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