DEV Community

Jan Küster 🔥
Jan Küster 🔥

Posted on

1 2

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?

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay