Is this default value of argument in es6?
function list({ skip = 0, limit = 50 } = {}) {
}
What does the above code do?
if it's list(skip=0, limit=50) I can understand but now I'm confused.
That function has destructuring and default parameters mixed together.
Based on the function signature, we can say that we're expecting a single argument, which should be an object.
function list(myObject) {
}
If no arguments are passed (or undefined is passed), we setup a default value to be an empty object, {}.
function list(myObject = {}) {
}
Now, no matter if we pass an object, no arguments, or undefined, myObject will be an object.
// myObject will be {} for all 3 calls
list({})
list()
list(undefined);
Next, we destructure this myObject by extracting skip and limit from it:
function list(myObject = {}) {
  let { skip, limit } = myObject;
}
Furthermore, we can perform this destructuring directly instead of the myObject parameter:
function list({ skip, limit } = {}) {
}
Finally, in case skip or limit do not exist on the value we end up with, we give them default values:
function list({ skip = 0, limit = 50 } = {}) {
}
                        The function is expecting an object, with skip and limit properties, and setting defaults if not present. See an example usage below to understand it more clearly
function list({ skip = 0, limit = 50 } = {}) {
  console.log(skip);
  console.log(limit);
}
// No args
list();
// skip changed. Note the object
list({skip: 2});
// limit changed. Note the object
list({limit: 2});
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