visit
let newarr = ["Red", "Yellow"];
let otherarr = ["Blue", ...newarr, "Green"]
console.log(otherarr); // ["Blue", "Red", "Yellow", "Green"];
So let’s explain what is happening here, newarr is an array containing two strings Red and Yellow, then the second array otherarr contains two strings and the newarr. Usually, when we add this array without the three periods operator it will add the new array into the other array. But as we have the spread operator it will add the element of the array into the other array.
function addThreeNumbers(x,y,z){
return x+y+z;
}
let args = [1,2,3];
addThreeNumbers(...args); // 6
Another use case is that you can pass an element of an array as a function. in the above example, we have a function addThreeNumbers with three parameters x,y,z which return the sum of these three numbers. Now we have an array with three values 1,2,3. In a normal state, we can pass three arguments to the function but with the help of the spread operator, we just pass the array with the three-dot operator (…), which will spread out the array to each element of the function.
function addThreeNumbers(x,y,z){
return x+y+z;
}
let args = [1,2,3,4];
addThreeNumbers(...args); // 6
.
let arr1 = [1,2,3];
let arr2 = [...arr1]
let arr1 = [1,2,3];
let arr2 = [5,6,7];
arr1.concat(arr2); // [1,2,3,5,6,7]
arr1 = [...arr1 ...arr2]; // [1,2,3,5,6,7]
Another use case is that we can concatenate arrays together, normally how we do this, is we use the concat method to concatenate arrays. With the spread operator, we can concatenate arrays too.
Lead image generated with stable diffusion.