1// spread operators can be used for arrays or objects
2
3// cloning to prevent mutation.
4let numList = [1,2,3];
5let numListClone = [...numList]; // [1, 2, 3]
6
7// spread operator for destructuring.
8let animal = {
9 name: 'dog',
10 color: 'brown',
11 age: 7
12};
13let { age, ...otherProperties } = animal;
14
15// spread operator as rest operator
16function sum(x, y, ...rest) {}
17
18// spread operator for merging arrays or objects
19let numLists = [...numList1, ...numList2];
20let animalWithBreed = {
21 ...animal,
22 breed: '',
23}
1let arr1 = ['A', 'B', 'C'];
2
3let arr2 = ['X', 'Y', 'Z'];
4
5let result = [...arr1, ...arr2];
6
7console.log(result); // ['A', 'B', 'C', 'X', 'Y', 'Z']
8// spread elements of the array instead of taking the array as a whole
1obj = {first_name : "Marty",
2 lovers: ["Jennifer Parker","Baines McFly"]
3 };
4let objClone = { ...obj }; // pass all key:value pairs from an object
5
6console.log(objClone)
7// { first_name: "Marty", lovers: ["Jennifer Parker", "Baines McFly"] }
1// seperate each element of array using ...
2let list = ['a','b','c'];
3let copy = [...list, 'd', 'e']; // ['a', 'b', 'c', 'd', 'e']
4//use for infinite parameters to a function
5function toDoList(...todos) {
6 //todos is an array, so it has map function
7 document.write(
8 `<ul>${todos.map((todo) => `<li>${todo}</li>`).join("")}</ul>`
9 );
10}
11toDoList("wake up", "eat breakfast", ...list); //ul containing: wake up eat breakfast a b c