In this JavaScript lesson we are going to talk about JavaScript Spread Operator, so it is used with arrays and its syntax is exactly the same as that of Rest Operator. and it is used to split the content of an array.
Let’s create an example.
1 2 3 4 5 6 7 |
let a = [1,2,3,4,5]; let b = [6,7,8,9]; let c = [...a, ...b] console.log(c); |
Also we can use with the strings.
1 2 3 |
let hello = ['Hello', 'World']; console.log(hello); console.log(...hello); |
Some time we need to convert a string in to list of characters, than we can use spread operator.
1 2 3 4 |
let name = "Parwiz"; console.log(name); console.log(...name); |
We can use spread operator with the objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
let obj1 = { name:'Parwiz', lastname:'Forogh' }; let obj2 = { email:'par@gmail.com', phone: 123456, ...obj1 }; console.log(obj2); |
JavaScript Spread Operator Features
Spread operator in JavaScript is represented by three dots (…) and is used to expand an iterable such as an array or an object into individual elements. these are some features of spread operator in JavaScript along with commented code examples:
- Copying Arrays: The spread operator can be used to make shallow copy of an array.
1 2 3 4 5 |
const numbers = [1, 2, 3]; const copyOfNumbers = [...numbers]; console.log(numbers); // Output: [1, 2, 3] console.log(copyOfNumbers); // Output: [1, 2, 3] |
In this example, the spread operator is used to create new array with the same elements as the original array numbers.
- Merging Arrays: the spread operator can be used to merge two or more arrays into single array.
1 2 3 4 5 |
const numbers1 = [1, 2, 3]; const numbers2 = [4, 5, 6]; const allNumbers = [...numbers1, ...numbers2]; console.log(allNumbers); // Output: [1, 2, 3, 4, 5, 6] |
In this example, the spread operator is used to combine the elements of numbers1 and numbers2 into new array called allNumbers.
- Passing Arguments: The spread operator can be used to pass the elements of an array as arguments to function.
1 2 3 4 5 6 |
function sum(a, b, c) { return a + b + c; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); // Output: 6 |
In this example the spread operator is used to pass the elements of the numbers array as individual arguments to the sum function.
- Copying Objects: The spread operator can be used to make a shallow copy of an object.
1 2 3 4 5 |
const person = { name: "John", age: 30 }; const copyOfPerson = { ...person }; console.log(person); // Output: { name: 'John', age: 30 } console.log(copyOfPerson); // Output: { name: 'John', age: 30 } |
In this example, the spread operator is used to create a new object with the same properties as the original object person.
Overall, the spread operator in JavaScript provides a lot of flexibility and can simplify code in many situations.