Hello Folks,
Let's see about javascript spread operator, syntax and examples.
What is ...Spread Operator?
The spread operator is a new addition to the set of operators in JavaScript ES6. It takes an iterable(e.g an array) and expands it into individual elements. The spread operator is commonly used to make copies of JS objects.
This operator makes the code concise and enhances its readability.
Syntax
The spread operator is denoted by three dots, ... Let's see the syntax below.
let myArray = ['I', 'N', 'D', 'I', 'A']
...myArray = 'I', 'N', 'D', 'I', 'A'
Let's see how to implement spread operator,
Example - Copying an array
The newArray has the element of myArray copied into it. Any changes made to myArray will not be reflected in newArray and vice versa.
let myArray = ['I', 'N', 'D', 'I', 'A']
let newArray = [...myArray]
console.log(newArray); // ['I', 'N', 'D', 'I', 'A']
Example - Insert the elements
It can be seen that the spread operator can be used to append one array after any element of the second array.
let oddNumbers = [1, 3, 5]
let combineWithEven = [2, 4, 6, ...oddNumbers]
console.log(combineWithEven); // [2, 4, 6, 1, 3, 5]
There is no limitation, You can append not only in the beginning or the end of the oddNumbers array.
let numbers = [3, 5]
let oddNumbers = [1, ...oddNumbers, 7, 9]
console.log(oddNumbers); // [1, 3, 5, 7, 9]
Example - Math object
Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments. Instead of having to pass each element like numbers[0], numbers[1], and so on, the spread operators allow array elements to be passed in as individual arguments.
let numbers = [0, 150, 30, 20, -8, -200]
console.log(Math.max(...numbers)); // 150
let numbers = [0, 150, 30, 20, -8, -200]
console.log(Math.min(...numbers)); // -200
Example - Merging objects
Not only merging an array like the example before, but you can also merge the object using javascript spread operators like this.
const circle = {
radius: 10,
}
const style = {
backgroundColor: 'red',
}
const solidCircle = {
...circle,
...style,
}
console.log(solidCircle); // { radius: 10, backgroundColor: 'red' }
That's it. Now we have understood what is spread operator, syntax, and some examples of spread operator.
I hope you find this post helpful and Thank you for reading. Do Explore!