— JavaScript, beginner, tutorial, learn-modern-javascript — 1 min read
By the end of this tutorial, you will be able to:
...
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.
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; // 103b; // 204pairs; // { 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.
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.
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!