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
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?
CodePudding user response:
The difference is that the default destructuring syntax will assign 1 only if the property is 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.