JS/ES6: Destructuring of undefined

I'm using some destructuring like this:

const { item } = content
console.log(item)

But how should I handle content === undefined - which will throw an error?

The 'old' way would look like this:

const item = content && content.item

So, if content is undefined -> item will also be undefined.

Can I do something similar using destructuring?

Answers:

Answer

You can use short circuit evaluation to supply a default if content is a falsy value, usually undefined or null in this case.

const content = undefined
const { item } = content || {}
console.log(item)                       // undefined

A less idiomatic (see this comment) way is to spread the content into an object before destructuring it, because null and undefineds values are ignored.

const content = undefined
const { item } = { ...content }
console.log(item) // undefined

If you are destructuring function params you can supply a default (= {} in the example).

Note: The default value would only be applied if the destructured param is undefined, which means that destructuring null values will throw an error.

const getItem = ({ item } = {}) => item
console.log(getItem({ item: "thing" })) // "thing"
console.log(getItem())                  // undefined

try {
  getItem(null)
} catch(e) {
  console.log(e.message)                // Error - Cannot destructure property `item` of 'undefined' or 'null'.
}

Or even set a default value for the item property if the input object doesn't contain the property

const getItem = ({ item = "default" } = {}) => item
console.log(getItem({ item: "thing" })) // "thing"
console.log(getItem({ foo: "bar" }))    // "default"

Answer

accepted answer does not work for truely undefined values which were not set by const content = undefined. in such cases this will work:

const { item } = (typeof content !== 'undefined' && content) || {}
console.log(item)
Answer
const { item } = Object(content)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.