Destructuring function parameters is so handy:
const fn = ({ foo, bar }) => console.log(foo, bar)
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
}
}
b) default to empty Object?
const fn = ({ foo, bar } = {}) => console.log(foo, bar)
If so, do you also default the Object's parameters to defaults? Like so:
const fn = ({ foo = {}, bar = {} } = {}) => console.log(foo.y, bar.x)
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)
}
This obviously is not really the same parameter destructuring as in the original example.
d) Something else?
Top comments (0)