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?

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up