DEV Community

Jan Küster
Jan Küster

Posted on

Do you default to empty Object when destructuring function parameters?

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?

Top comments (0)