Mixing Default Parameters and Destructuring…it’s a thing

I’ve had my first “What, I can do that?” moment of 2017 and felt I needed to share it!

Why I hesitate to use destructuring in functions

I typically don’t destructure arguments in a function unless I can guarantee the state of the object. For instance, I know Angular $http responses will always follow a given pattern, and I can rely on that fact.

In my current project, there are many helper functions throughout the app that cannot guarantee state. I came across a scenario (I’ve changed the properties for the sake of IP protection)

Clearly there is a case where we have an undefined toCheck, and it could potentially have no options.

Eliminating the undefined case

We can eliminate the undefined toCheck case by giving it a default parameter of {}. Giving us the signature: (toCheck = {}) =>. To me, this was where I would have stopped had I not been curious....

I then tried to do:(toCheck = { options = [] }), but now options is only an empty array when toCheck is undefined. Had I done this to eliminate the entire if statement, it would end up having a runtime error when {} is passed as toCheck.

Mixing Default Parameters with Destructuring

And then, eureka! I figured it out. It turns out, ES6 allows for mixing the default parameter and destructuring operations into a single statement. It’s a weird & ugly syntax, if I’m being honest, but I still think it is more concise than an additional if statement & having two return statements.

The code from above could be rewritten as:

On top of this, it is also possible to rename the options property using the destructuring syntax, which I have chosen not to.


When the argument is undefined, the following will happen:

  1. The argument is undefined, so therefore it falls back to the default
  2. It then attempts to destructure the {}, to find that options is undefined
  3. Since options is undefined, it uses the default of []
  4. [] is then assigned onto the options variable

Another scenario being checked for in the if statement is whether or not the property options existed. The scenario to test this would be to pass in {}.

The behavior would be the same as steps 3 and 4 of the above process.

Front End Developer