ES6 Rest Parameters: Handling Function Arguments the Smart Way

ES6 Rest Parameters: Handling Function Arguments the Smart Way

Overview

In this tutorial, you will learn how to utilize JavaScript rest parameters to gather multiple function arguments effectively in an array.

Introduction to Rest Parameters

ES6 brought the rest parameter, represented by three dots (…), that enables functions to accept an indefinite number of arguments as an array.

Syntax

const fn = (a, b, ...args) => {
   // args is an array
};        

Here, a and b capture the first two arguments, and args gathers the rest as an array.

Example Usage:

fn(1, 2, 3, "A", "B", "C");        

In this case, args stores:

[3, "A", "B", "C"]        

If only two arguments are passed:

fn(1, 2);        

Then args is an empty array:

[]        

Rest Parameter Rules

  1. Must be the last parameter in a function definition:

const fn = (a, ...rest, b) => { // ? Syntax Error
};

//SyntaxError: Rest parameter must be last formal parameter        

More Examples:

1. Summing Numbers definition

const sum = (...args) => args.reduce((total, a) => total + a, 0);
console.log(sum(1, 2, 3)); // Output: 6        

2. Filtering Only Numbers

If arguments contain different data types, filter out only numbers:

const sum = (...args) => args
  .filter(e => typeof e === 'number')
  .reduce((prev, curr) => prev + curr, 0);

console.log(sum(10, 'Hi', null, undefined, 20)); // Output: 3        

Rest Parameters vs Arguments Object

Arguments object is present in legacy functions but is not an actual array, and therefore does not include array methods such as filter() and reduce().

Example Without Rest Parameters (Using arguments)

function sum() {
  return Array.prototype.filter.call(arguments, e => typeof e === 'number')
    .reduce((prev, curr) => prev + curr, 0);
}        

Rest parameters make the code more readable and modern.??

Filtering Arguments by Type

const filterBy = (type, ...args) => args.filter(e => typeof e === type);        

Rest Parameters with Arrow Functions

Arrow functions do not have an arguments object, so the rest of the parameters are necessary:

const combine = (...args) => args.join(" ");
console.log(combine("JavaScript", "Rest", "Parameters")); // Output: "JavaScript Rest Parameters"        

Rest Parameters in Dynamic Functions

You can use rest parameters in functions created dynamically with the Function constructor:

const showNumbers = new Function('...numbers', 'console.log(numbers)');
showNumbers(1, 2, 3); // Output: [1, 2, 3]        

Conclusion

  1. Rest parameters permit functions to receive any amount of arguments as an array.

2. They have to be the last parameter of a function.

3. Unlike arguments, rest parameters are actual arrays and do include array methods.

要查看或添加评论,请登录

Honufa Khatun的更多文章

社区洞察

其他会员也浏览了