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

Difference between initializing using ternary condition vs bracket initialization

I just come across of this variable initialization

let { page = 1 } = req.query;

where if req.query.page doesn’t exist, page = 1. But if there is req.query.page (let say 6), page = 6

I just want to ask if there is any difference the above initialization on this

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

let page = req.query.page? req.query.page : 1

and at this point I like using the first since it’s less in code. Any idea how the first one works?

>Solution :

The difference is that the default destructuring syntax will assign 1 only if the property is null or undefined. In contrast, the conditional operator will assign whenever the property is falsy.

const req = { query: {
  page: 0
}};

let { page = 1 } = req.query;
console.log(page);
const req = { query: {
  page: 0
}};

let page = req.query.page? req.query.page : 1
console.log(page);

So it’s slightly different, but doing let { page = 1 } = req.query; should be fine as long as you keep in mind what it means.

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