DEV Community

loading...

Do you default to empty Object when destructuring function parameters?

Jan Küster
Graduated in Digital Media M.Sc. now developing the next generation of educational software. Since a while I develop full stack in Javascript using Meteor. Love fitness and Muay Thai after work.
・1 min read

Destructuring function parameters is so handy:

const fn = ({ foo, bar }) => console.log(foo, bar)
Enter fullscreen mode Exit fullscreen mode

However, calling with no args yields to TypeError: Cannot destructure property 'foo' of '_ref' as it is undefined.

How do you approach this (consistently; by convention)?

a) just let the code run into this error and let it bubble up to a higher-order try-catch?

const fn = ({ foo, bar }) => console.log(foo, bar)

exort const whatever = function (argsFromOutside) {
  try {
    return fn(argsFromOutside)
  } catch (e) {
    // log error etc.
    return null
  }
}
Enter fullscreen mode Exit fullscreen mode

b) default to empty Object?

const fn = ({ foo, bar } = {}) => console.log(foo, bar)
Enter fullscreen mode Exit fullscreen mode

If so, do you also default the Object's parameters to defaults? Like so:

const fn = ({ foo = {}, bar = {} } = {}) => console.log(foo.y, bar.x)
Enter fullscreen mode Exit fullscreen mode

I had this particular case and it made the code more and more unreadable...

c) destructure inside the function

const fn = (args) => {
  if (!args) return
  const { foo, bar } = args
  console.log(foo, bar)
}
Enter fullscreen mode Exit fullscreen mode

This obviously is not really the same parameter destructuring as in the original example.

d) Something else?

Discussion (0)