Skip to content
Code with Hou

Learn Modern JavaScript - Rest & Spread

JavaScript, beginner, tutorial, learn-modern-javascript1 min read

Introduction

By the end of this tutorial, you will be able to:

  • use rest parameters to collect an arbitrary number of property keys in an object into a new object
  • apply the spread operator to create a shallow copy of an object

Rest Parameters and Spread Syntax with ...

Depending on the context in which the syntax ... is used, it can either be used as rest parameters or spread syntax. You can use rest and spread with arrays or objects.

Rest Parameters

The "rest" parameters can collect an arbitrary number of property keys in an object into a new object:

1let { a, b, ...pairs } = { a: 10, b: 20, c: 30, d: 40 };
2a; // 10
3b; // 20
4pairs; // { c: 30, d: 40 }

The rest element must come last in the destructuring order, so let { ...pairs, a, b } = { a: 10, b: 20, c: 30, d: 40 }; won't work.

Spread Syntax

The spread syntax unpacks the collected elements into a new object. Therefore, you can use spread ... to clone the properties from one object to another.

Take a look at the code below.

1const person = { name: "Hou", title: "software engineer" };
2const personalInfo = { age: 32, location: "Brooklyn, NY" };
3
4const employee = {
5 id: 1,
6 department: "engineering",
7 ...person,
8 ...personalInfo,
9};
10
11console.log(employee);

If you run the code above, you will get back the following object:

1Object {
2 id: 1;
3 department: 'engineering';
4 name: 'Hou';
5 title: 'software engineer';
6 age: 32;
7 location: 'Brooklyn, NY';
8}

As you can see, the employee object contains the name and title properties from the person object, and the age and location properties from the personalInfo object.

NOTE: The spread operator performs a shallow copy, not a deep copy of an object.

Want more content like this? Subscribe to get the latest updates in your inbox

Share your Feedback

What did you like or didn't like about this post? Let me know what worked well and what can be improved. Your feedback is much appreciated!