Spread Operator in ES6 is three dot(…) to make a copy of array without alter or muted the original array
Example
var array1 = [“Tallac”, “Ralston”, “Rose”]
var array2 = [“Ward”, “Blackwood”]
var array3 = […array1, …array2]
console.log(array3.join(‘, ‘)) // Tallac, Ralston, Rose, Ward, Blackwood
Without the Spead Operator(…) the reverse() method to get the last element from array. it alter the original array
Example:
var array1= [“Tallac”, “Ralston”, “Rose”]
var [last] = array1.reverse()
console.log(last) // Rose
console.log(peaks.join(‘, ‘)) // Rose, Ralston, Tallac
But with spead operator(…). it does not alter the original array. its make the copy of original array
Example:
var array1= [“Tallac”, “Ralston”, “Rose”]
var [last] = […array1].reverse()
console.log(last) // Rose
console.log(peaks.join(‘, ‘)) // Tallac, Ralston, Rose
We can also use the spread operator to collect function arguments as an array. in the given below example .we build a function that takes in n number of arguments using the spread operator
function city(...args) {
var [start, ...remaining] = args
var [finish, ...stops] = remaining.reverse()
console.log(`drive through ${args.length} towns`) // drive through 5 towns
console.log(`start in ${start}`) // start in delhi
console.log(`the destination is ${finish}`) //the destination is deoria
console.log(`stopping ${stops.length} times in between`) //stopping 4 times in in between
}
city("delhi", "mumbai","ghaziabad","noida","deoria")