Search code examples
javascriptecmascript-6destructuring

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?


Solution

  • You can use the default value inside destructuring

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