ES6/ES2015 For Newbies Lesson 4: Spread and Rest Parameters

Share:
Source Code

Are you tired of splicing, spiting, and concatenating arrays? Array manipulation is one of the most common things a developer does daily.  To help with that, Javascript provided us with language level APIs like Array.split, Array.splice, Array.slice, and Array.concat. While the APIs are very useful, they’re not exactly friendly to use, even for an experienced programmer, they still need to look them up sometimes to understand the differences.

ES6 Spread and Rest operators

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables  (for destructuring assignment) are expected. – MDN

Let’s look at an example:

let dietSodas = ['diet coke', 'diet pepsi', 'diet sprite'];
let sodas = ['coke', ...dietSodas, 'sunkist', 'mountain dew'];
console.log(sodas);	// ["coke", "diet coke", "diet pepsi", "diet sprite", "sunkist", "mountain dew"]

In the example above, the spread operator is indicated by  in front of a variable …dietSodas.  We’re inserting the content of the dietSodas array into the sodas array at a specific location, and the resulting array is a modified version of sodas that contains elements from dietSodas.

You can also push to an existing array like this:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

arr1.push(...arr2);
console.log(arr1);	// [1, 2, 3, 4, 5, 6]

Here’s how you can use spread to map to function parameters:

function sumOfThreeValues(a, b, c) {
	return a + b + c;
}

let numberList = [1, 2, 3];
console.log(sumOfThreeValues(...numberList));	// 6

Accessing function parameters with ease

In ES5, often times you would need to access an arbitrary number of parameters of a function:

function parameterLogger() {
	return Array.prototype.slice.call(arguments, parameterLogger.length);
}

let params = parameterLogger(1,2,3,4,5);
console.log(params);

you can do the same in with rest parameters like so:

// ES6 with Rest parameter
function parameterLogger(...args) {
	// args is an array of all the arguments provided to the function
	return args;
}

let params = parameterLogger(1,2,3,4,5);
console.log(params);

No more .call nonsense and much easier to read!

Here’s a fun little function that adds a number(first parameter) to each subsequent parameters:

// Make functions easier to write
function adder(numToAdd, ...args) {
	return args.map((arg) => numToAdd + arg);
}

var ans = adder(1,2,3);	// [3, 4]
console.log(ans);

That is it for this tutorial, it’s a short one.  Hopefully this convinces you to start using them today!

[frames playlist=’3′]

Comments Or Questions? Discuss In Our Discord

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

More from PentaCode