Home > Web Front-end > JS Tutorial > Spread & Rest Operator

Spread & Rest Operator

WBOY
Release: 2024-08-21 06:10:05
Original
1222 people have browsed it

Spread & Rest Operator

  • Form a new array from an existing array with less character noise.
  • Spread extracts the elements as values. Its an Immutable function.
  • [] is the way to write new arrays. Hence, spread doesn't alter the original array.
  • Spread works on all iterables, not just on arrays.
  • Iterables: String, Array, Map, Set i.e mostly builtin data structures except object data-type.
  • Difference from Destructuring: Extracts all the elements from an array, and doesn't create new variables, only used at places which require values CSVs.
  • USED when we are building an array, or when we pass values into a function.
const nums = [5,6,7];
const newNums = [1,2, nums[0],nums[1],nums[2]];
console.log(newNums); // [ 1, 2, 5, 6, 7 ]

is reduced to 

const nums = [5,6,7];
const newNums = [1,2, ...nums];
console.log(newNums); // [ 1, 2, 5, 6, 7 ]
console.log(...newNums); // 1 2 5 6 7
Copy after login

1. Merge two arrays together

const arr1 = [1,2,3,4,5];
const arr2 = [6,7,8,9];

let nums = [...arr1,...arr2];
nums; // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]


const firstname = "Peter";
const fullName = [...firstname,' ',"P."];
fullName; // [ 'P', 'e', 't', 'e', 'r', ' ', 'P.' ]

console.log(...firstname); // 'P' 'e' 't' 'e' 'r'
Copy after login
  • SOURCE of ERROR: Spread operator doesn't work inside a template string as template string doesn't expect multiple values inside it.

2. Creating Shallow Copies of arrays

const girl = {
  name: 'Melania',
  friends: ['Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya']
};

const frnz = [...girl.friends];
console.log(frnz); // [ 'Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya' ]
console.log(girl.friends); // [ 'Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya' ]
Copy after login

Spread works on objects also even though they are not iterables.

let male = {
  "firstName": "Gangadhar",
  "lastName": "Shaktimaan"
}

let female = {
  "firstName": "Geeta",
  "lastName": "Vishwas"
}

let x = {...male, born: 1950};
let y = {...female, born: 1940};

x; // { firstName: 'Gangadhar',   lastName: 'Shaktimaan',   born: 1950 }
y; // { firstName: 'Geeta',  lastName: 'Vishwas',  born: 1940 }```




## Shallow Copy of objects:

let male = {
  "firstName": "Gangadhar",
  "lastName": "Shaktimaan"
}

let character = {...male, firstName: 'Wonderwoman'};

male;         // { firstName: 'Gangadhar', lastName: 'Shaktimaan' }
character;    // { firstName: 'Wonderwoman', lastName: 'Shaktimaan' }

- First name for character object is changed although it was extracted from male object


Copy after login

Rest Pattern & Rest Parameters:

  • Rest does the opposite of spread but has a same syntax like spread.
  • Spread was used to build new arrays or pass values to a fn. in both cases, spread was used to expand elements in both cases.
  • Rest uses the same syntax but to condense those values into a single
  • Spread is for unpacking elements from an array, rest is for packing elements into an array. ```

Difference in syntax of spread and rest operator:
Spread operator => ... are used on RHS of assignment operator.
const nums = [9,4, ...[2,7,1]];

Rest operator => ... will be on the LHS of assignment operator with destructuring
const [x,y,...z] = [9,4, 2,7,1];

## Rest syntax collects all the elements after the last elements into an array. Doesn't include any skipped elements. 
- Hence, it should be the last element in the destructuring assignment.
- There can be only one rest in any destructuring assignment.
Copy after login

let diet = ['pizza', 'burger','noodles','roasted','sushi','dosa','uttapam'];

let [first, ,third, ...others] = diet;
first;
third;
others;

- Rest also works with objects. Only difference is that elements will be collected into a new object instead of an arrray.
Copy after login

let days = { 'mon':1,'tue':2,'wed':3,'thu':4,'fri':5,'sat':6,'sun':7};
let {sat, sun, ...working} = days;
let off = {sat, sun};

working; // { mon: 1, tue: 2, wed: 3, thu: 4, fri: 5 }
off; // { sat: 6, sun: 7 }

- Although both look same, but they work differently based on where they are used.

Copy after login

Subtle Distinction b/w Rest & Spread:

  • Spread operator is used where we would write values separated by commas
  • Rest pattern is used we would write variables names separated by commas.

Copy after login

The above is the detailed content of Spread & Rest Operator. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template