Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what does const {foo=20} = bar mean in javascript?

I couldn’t find anything to search on for this. Based on my limited testing it looks like after

const {foo = 20} = bar

foo will have the value bar.foo if it exists otherwise it will have the value 20, i.e. it’s equivalent to:

const foo = bar?.foo ?? 20

is my understanding correct?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No it’s not exactly equivalent.

Difference:

With ({foo = 20}), default value is used if bar.foo is undefined, but not if bar.foo is null.

const {foo = 20} = bar

With (??), the default value is used for null or undefined.

const foo = bar?.foo ?? 20
let bar = { foo: null };
const { foo = 20 } = bar;
console.log(foo); // null (not 20)

bar = { foo: null };
const fooVal = bar?.foo ?? 20;
console.log(fooVal); // 20
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading