Monday, April 16, 2018

Rest parameters ...


A function can be called with any number of arguments. What is this means? Assume that you one simple sum function which accept two parameters. So you can pass those two parameters easily. But Suppose if it is more than 5 parameters or more than 10 parameters. You will get lazy to pass manually, right ? To avoid that use rest parameter.

Simple Example I:
function sumAll(...args) { // args is the name for the array
  let sum = 0;

  for (let arg of args) sum += arg;

  return sum;
}

alert( sumAll(1) ); // 1
alert( sumAll(1, 2) ); // 3
alert( sumAll(1, 2, 3) ); // 6

The rest parameters should be mentioned as three dots .... Here ...args is array which have all of your arguments.

Suppose if you dont want all n parameters as ...args, you can give first two as manual and remainig all as ...args.

Simple Example II:

function showName(firstName, lastName, ...titles) {
  alert( firstName + ' ' + lastName ); // TestFirstName TestLastName

  // the rest go into titles array
  // i.e. titles = ["ArrayFirst", "ArraySecond"]
  alert( titles[0] ); // ArrayFirst
  alert( titles[1] ); // ArraySecond
  alert( titles.length ); // 2
}

showName("TestFirstName", "TestLastName", "ArrayFirst", "ArraySecond");


Note: Remember, the ...rest must always be last.






No comments:

Post a Comment