ES6 rest parameters and extension operators

Keywords: Javascript REST Attribute less

rest parameters and extension operators are new features of ES6.
The rest parameter takes the form of:... Variable name; the extension operator is three points (...).

rest parameter

The rest parameter is used to get the redundant parameters of the function so that the arguments object is not needed. The rest parameter collocation variable is an array, which puts the redundant parameters into the array.

function add(...values) {
  let sum = 0;
  for (var val of values) {
    sum += val;
  }
  return sum;
}

add(1, 2, 3) // 6

A set of parameter values passed to the add function are integrated into an array of values.

Here is an example of a rest parameter replacing arguments variables.

// The Writing of arguments Variables
function sortNumbers() {
  return Array.prototype.slice.call(arguments).sort();
}

// Writing of rest parameter
const sortNumbers = (...numbers) => numbers.sort();

Differences between rest parameters and arguments objects

  • The rest parameter contains only those parameters that do not correspond to the formal parameter; the arguments object contains all the arguments passed to the function.

  • The arguments object is not a real array; the rest parameter is a real Array instance, which means that you can use all array methods directly on it.

  • The arguments object object also has additional attributes (such as callee attributes).

In addition, two points should be noted when using rest parameters:

  • The rest parameter cannot be followed by any other parameter (that is, the last parameter only), otherwise an error will be reported.

function f(a, ...b, c) { ... } // Report errors
  • The length attribute of the function, excluding the rest parameter.

(function(a) {}).length  // 1
(function(...a) {}).length  // 0
(function(a, ...b) {}).length  // 1

Extended Operator

Extended operators can be seen as inverse operations of rest parameters, converting an array into comma-separated parameter sequences.

console.log(...[1, 2, 3]) // 1 2 3

console.log(1, ...[2, 3, 4], 5) //1 2 3 4 5

Application of Extended Operator

Ordinary function calls

function push(array, ...items) {
  array.push(...items);
}

function add(x, y) {
  return x + y;
}

var numbers = [4, 38];
add(...numbers) // 42

In the above code, array.push(...items) and add(...numbers) are both calls to functions, and they all use extension operators. This operator converts an array into a sequence of parameters.

Call functions instead of apply methods

// Writing of ES5
Math.max.apply(null, [14, 3, 77])

// Writing of ES6
Math.max(...[14, 3, 77])

// Equivalent to
Math.max(14, 3, 77);
// Writing of ES5
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);

// Writing of ES6
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);

Merge arrays

var arr1 = ['a', 'b'];
var arr2 = ['c'];
var arr3 = ['d', 'e'];

// Merged array of ES5
arr1.concat(arr2, arr3)  // [ 'a', 'b', 'c', 'd', 'e' ]

// Merged array of ES6
[...arr1, ...arr2, ...arr3]  // [ 'a', 'b', 'c', 'd', 'e' ]

Combining with Deconstruction Assignment

const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest  // [2, 3, 4, 5]

const [first, ...rest] = [];
first // undefined
rest  // []

const [first, ...rest] = ["foo"];
first  // "foo"
rest   // []

If the extended operator is used for array assignment, it can only be placed in the last position of the parameter, otherwise, an error will be reported.

const [...butLast, last] = [1, 2, 3, 4, 5];  // Report errors

const [first, ...middle, last] = [1, 2, 3, 4, 5];  // Report errors

Converting strings to arrays

var str = 'hello';

// ES5  
var arr1 = str.split('');  // [ "h", "e", "l", "l", "o" ] 

// ES6  
var arr2 = [...str];  // [ "h", "e", "l", "l", "o" ] 

Objects Implementing Iterator Interface

whatever Iterator Objects of the interface can be converted to real arrays using extension operators.

var nodeList = document.querySelectorAll('div');
var array = [...nodeList];

In the code above, the querySelectorAll method returns a nodeList object. It is not an array, but an object similar to an array. At this point, the extension operator can turn it into a real array because the NodeList object implements Iterator.

summary

As can be seen from the examples above, rest parameter usage scenarios should be a little less, mainly dealing with variable number of parameters, which can avoid the use of arguments objects. The application of extended operators is more extensive, flexible in practical projects, can write more streamlined code.

Posted by galafura on Wed, 12 Jun 2019 18:15:04 -0700