HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

3) Connect Four Lesson

Understanding JavaScript's Spread and Rest Syntax

9 min to complete · By Ian Currie

In this lesson, you will learn about the spread and rest syntax.

The spread and rest syntax is often used with destructuring assignments. It's a great way to make your code more concise and readable. It may look strange at first, but once you get used to it, you won't want to live without it.

The Rest Syntax

As you saw in the previous lesson on destructuring assignment, you can assign the elements of an array into variables like this:

const row = [1, 2, 3, 4, 5];
const [a, b, c] = row;
console.log(a, b, c); // 1, 2, 3

The rest syntax would allow you to assign the remaining elements of the array into another variable as an array:

const row = [1, 2, 3, 4, 5];
const [a, b, c, ...d] = row;
console.log(d); // [4, 5]

This also works for objects, creating a new object with the rest of the properties:

const person = {
	name: 'bill',
	age: 35,
	occupation: 'delivery driver',
	dwelling: 'flat'
};

const { name, age, ...otherDetails } = person;
console.log(otherDetails); // {occupation: 'delivery driver', dwelling: 'flat'}

This is called the rest syntax because it works by packing many values into one variable. It packs the rest of the values into a variable. Since it relies on having to know what the "rest" are, there can only ever be one per assignment, and it always must be the last item in the assignment.

The Spread Syntax

The spread syntax, on the other hand, will expand an array or object inside another structure:

const scoresClassA = [9, 5, 3, 6, 7, 4, 5, 9, 8, 5];
const scoresClassB = [5, 4, 3, 4, 6, 8, 9, 6, 8, 7];

const allScores = [...scoresClassA, ...scoresClassB];
console.log(allScores);
// [9, 5, 3, 6, 7, 4, 5, 9, 8, 5, 5, 4, 3, 4, 6, 8, 9, 6, 8, 7]

// or

const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
console.log(lyrics); // ['head', 'shoulders', 'knees', 'and', 'toes']

Objects can also be composed in this way:

let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };

let clonedObj = { ...obj1 };
// { foo: "bar", x: 42 }

let mergedObj = { ...obj1, ...obj2 };
// { foo: "baz", x: 42, y: 13 } Note how the second object overwrote `foo`

Use Spread Syntax to Copy Arrays or Objects

The spread syntax can be used to copy arrays or objects:

const arr = [1, 2, 3];
const arr2 = [...arr];

const obj = { foo: 'bar', x: 42 };
const obj2 = { ...obj };

Unlike direct assignment, where the references to arrays and objects are copied, the spread syntax will create a new array or object.

Note, however, that these are shallow copies. If the array or object contains other arrays or objects, those will still be references to the original:

const a = [
	[1, 2, 3],
	[4, 5, 6]
];
const b = [...a];

b[0][0] = 0;
console.log(a); // [[0, 2, 3], [4, 5, 6]]

Use Spread Syntax in Functions

This can also be used when working with functions. For example, if you want to unpack an array into the arguments of a function:

function sum(a, b, c) {
	return a + b + c;
}
const nums = [1, 2, 3];
const sumResult = sum(...nums);
console.log(sumResult); // 6

As you can see, since there are three arguments and 3 items in the array, you can spread them as the arguments to the function.

Another example is to initialize new Date objects:

const dateFields = [1970, 0, 1]; // 1st Jan 1970
const d = new Date(...dateFields);

Use Rest and Spread Syntax to Make Functions Accept an Arbitrary Number of Arguments

Combining rest and spread syntax can even help you to design your functions to accept an arbitrary number of arguments:

function sum(...nums) {	// rest syntax used to collect all args into an array
	return nums.reduce((sum, num) => sum + num);
}

const scores = [8, 4, 5, 3, 6, 7, 5, 4, 3];
sum(...scores); // 45

The function definition uses the rest syntax to assign all the variables that are passed into an array called nums. It then reduces the array to a sum.

The function call uses the spread syntax to explode the array into separate numbers.

Using this syntax, the function sum can now accept an arbitrary number of arguments!

Learn by Doing

Copy the examples from this lesson and get them working in your labs. Make a few variations, too.

If you're doing this course step-by-step, and especially if you're in the mentorship program, please be sure to push your work to GitHub when you're done.

Summary: What Is the JavaScript REST and Spread Syntax

In this lesson you've:

  • Discovered how the rest syntax can consolidate remaining array elements or object properties into a single variable, simplifying the process of handling multiple items.
  • Practiced using the rest syntax in both arrays and objects, noting its limitation of being used only once and as the last item in an assignment.
  • Explored the spread syntax for expanding an iterable's elements into another array or an object's properties into another object, which is handy for merging collections.
  • Learned that the spread syntax is very useful for copying arrays or objects, creating a new, shallow copy rather than referencing the original.
  • Experienced how to apply the spread syntax to function arguments, allowing you to pass arrays directly as separate arguments.
  • Saw the versatility of spread syntax combined with rest parameters in function definitions to accept any number of arguments and process them easily.