The Rest Parameter

A Rest Parameter is used as the last argument of a function declaration. It is enabling the user to specify any number of parameters.

function sumUp(...nums) {
	  return nums.reduce((acc, cur) => acc = Number(acc + cur), 0);
	}

	console.log(sumUp(1, 2, 3));
	// -> 6

A function can also have common parameters as long as the Rest Parameter is the last one.

	function myHero(name, level, ...abilities) {
	  return `My hero ${name} on level ${level} has the following abilities: ${abilities.join(", ") || 'none'}.`;
	}

	console.log(myHero('Arthas', 55, 'Attack', 'Blizzard'));
	// -> My hero Arthas on level 55 has the following abilities: Attack,Blizzard.

	console.log(myHero('Thrall', 1));
	// -> My hero Thrall on level 1 has the following abilities: none.

Rest Parameter vs. Arguments

Arguments is an Array-like Object; we cannot directly apply Array-functions to it. We have to make use of the Spread Operator to unfold the Arguments Object in an Array first. For instance: In the last example, we could apply the join method directly to our abilities parameter.

function sumUp() {
	  return [...arguments].reduce((acc, cur) => acc = Number(acc + cur), 0);
	}

	console.log(sumUp(1, 2, 3));
	// -> 6

#spread-operator #es6 #rest-parameter #learn-javascript #javascript-basics #javascript

Rest Parameter and Spread Operator
2.20 GEEK