Search code examples
javascriptdestructuring

JavaScript: Error when destructuring an array of objects when the array is empty


What is the cleanest way of getting around this scenario?

Considering I have an array of objects:

let originalArray = [{
  personName: 'Ben'
}];

I can destructure like this:

const [{
  personName: name
}] = originalArray;

console.log(name); // "Ben"

However, if originalArray is empty...

let originalArray = [];

const [{
  personName: name
}] = originalArray;

I get this error

Uncaught TypeError: Cannot destructure property `personName` of 'undefined' or 'null'

I've found some articles/docs explaining how to handle errors when destructuring just an object, but not if it's an array of objects, and the array is empty.


Solution

  • You can set default values for undefined properties

    const [{
      personName: name = ''
    } = {}] = originalArray;
    
    console.log(name); // ""