How can I destructure an object only if it is defined ?
const {url} = image; // only destructure if image is defined.
// don't want to nest the destructuring in if image condition
If by saying
only destructure if image is defined
You mean that it is declared for sure, then you can do this:
const {url} = image || {};
Running Examples:
let image;
const {url} = image || {};
console.log('url is',url);
const image = {url: 'someUrl.com'};
const {url} = image || {};
console.log('url is', url);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With