JavaScript Spread and Rest Operators

When I first started working with React, I started to see the spread and rest operators coming up constantly. I had not seen them before for some reason. The two operators are represented by three periods ... in JavaScript code. Coming from a PHP background, I was a little confused and didn’t know what they actually did. Turns out, they are extremely useful.

Spread operator

The spread operator takes an array and outputs the values as individual parameters. Take this example for instance:

let people = ['Matthew', 'Mark', 'Luke', 'John'];

function printPeople(one, two, three, four) {
	console.log(`${one} ${two} ${three} ${four}`);
}

printPeople(...people);

The spread operator works with objects too:

let vehicle = {
	make: 'Toyota',
	model: 'Tacoma'
};

console.log(
	{
		...vehicle,
		speed: 120
	}
);

Object properties will be overridden in the order that they are added. Look at this example:

let house = {
	bathrooms: 2,
	bedrooms: 4
};

console.log(
	{
		...house,
		bathrooms: 1
	}
);

// Will ouput the follow:
//{
//	bathrooms: 1
//	bedrooms: 4
//}

Rest operator

The rest operator does the opposite of the spread operator. It takes multiple values and passes them in to an array. Take a look at this example of this this works:

const printNames = (...names) => {
	console.log(names);
};

printNames('Matthew', 'Mark', 'Luke', 'John');

// This returns an array of:
// ["Matthew", "Mark", "Luke", "John"]

The rest operator will always return an array:

const printText = (...text) => {
	console.log(text);
};

printText();
// This returns an array of: []

And it can also be used in conjunction with standard function arguments.

const printNames = (first, second, ...names) => {
	console.log(first, second, names);
};

printNames('Matthew', 'Mark', 'Luke', 'John');

// This returns the following
// "Matthew", "Mark", ["Luke", "John"]

The rest operator is great for handling function arguments, but it also works well when destructuring arrays and objects.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *