close

[Solved] JS/ES6: Destructuring of undefined

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error JS/ES6: Destructuring of undefined in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How To Solve JS/ES6: Destructuring of undefined Error ?

  1. How To Solve JS/ES6: Destructuring of undefined Error?

    To Solve JS/ES6: Destructuring of undefined Error You can use short circuit evaluation to supply a default if the content is a falsy value, usually undefined or null in this case. A less idiomatic (see this comment) way is to spread the content into an object before destructuring it because null and undefined values are ignored. If you are destructuring function params you can supply a default (= {} in the example).

  2. JS/ES6: Destructuring of undefined

    To Solve JS/ES6: Destructuring of undefined Error You can use short circuit evaluation to supply a default if the content is a falsy value, usually undefined or null in this case. A less idiomatic (see this comment) way is to spread the content into an object before destructuring it because null and undefined values are ignored. If you are destructuring function params you can supply a default (= {} in the example).

Solution 1

You can use short circuit evaluation to supply a default if the 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 undefined 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).

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"

Solution 2

const { item } = Object(content)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment