Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destructure only if object is defined

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
like image 831
Lev Avatar asked Mar 13 '26 18:03

Lev


1 Answers

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);
like image 51
Sagiv b.g Avatar answered Mar 16 '26 08:03

Sagiv b.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!