Pete
Pete

Reputation: 3451

How have null returned in destructure vs throwing error

I have a JavaScript destructure like this that works:

const {
  data: {currentVal}
} = {
  data: {
    currentVal: "one"
  }
}

(working means currentVal is "one")

If data is not defined, my code errors with this:

error: Uncaught TypeError: Cannot read property 'currentVal' of undefined

That is, if I change the code to

const {
  dataxxx: {currentVal}
} = {
  dataa: {
    currentVal: "one"
  }
}

Is there some "?" type syntax I can use so that currentVal ends up undefined instead of throwing an error?

Upvotes: 0

Views: 46

Answers (1)

lissettdm
lissettdm

Reputation: 13078

You can use the default value inside destructuring

const { data: {currentVal} = {}} = {
  dataa: {
    currentVal: "one"
  }
}
console.log(currentVal);

Upvotes: 2

Related Questions