Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of argument in ES6

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.

like image 556
Jenny Mok Avatar asked Jun 12 '17 04:06

Jenny Mok


2 Answers

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 } = {}) {

}
like image 161
nem035 Avatar answered Oct 21 '22 06:10

nem035


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});
like image 34
maazadeeb Avatar answered Oct 21 '22 06:10

maazadeeb