11

Suppose I want to destructure my function argument like this

const func = ({field: {subField}}) => subField;

How can I prevent this from throwing an error if field is undefined or null ?

Lev
  • 13,856
  • 14
  • 52
  • 84

3 Answers3

11

You might use a default value:

const func = ({field: {subField} = {}}) => subField;

It works only with {field: undefined} though, not with null as a value. For that I'd just use

const func = ({field}) => field == null ? null : field.subField;
// or if you don't care about getting both null or undefined respectively
const func = ({field}) => field && field.subField;

See also javascript test for existence of nested object key for general solutions.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

You could only part destruction and use for subField a parameter with a check.

var fn = ({ field }, subField = field && field.subField) => subField;

console.log(fn({ field: null }));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

A good way to fix both the cases of null and undefined is the following

const func = ({field}) => {
   let subField = null;
   if(field) {
       ({subField} = field);
   }
   return subField
};

If you only want to handle the case when field is undefined, you could just to

const func = ({field: {subField} = {}}) => subField;

whereby if field is undefined the default empty object is used as its value

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400