Search code examples
javascriptreact-nativeecmascript-6destructuring

Is it possible to check if the object is available before Destructuring?


I have an object of values to Destructure, But before doing so i would like to check if the object is available,

const  { contactno, contactemail } =  this.props.app.user;

In this case the object user is not available always, Due to this I am getting following error,

TypeError: Cannot read property 'contactno' of undefined.

Hence, Is there nay way to check if the object is available before Destructure?


Solution

  • using AND and OR operator you can safely destructure object like this.

    const  { contactno, contactemail } =  (this.props.app && this.props.app.user) || {};