The Spread Operator (...)

The Spread Operator (...)

We can use the Spread operator to expand an array into all its elements. unpacking all the array elements into one.

Example :

const arr = [7,8,9]console.log(...newArr);
const badArr = [1,2,arr[0],arr[1],arr[2]]
console.log(badArr); //1,2,7,8,9

//using spread operator

const newArr = [1,2, ...arr];
console.log(newArr);//1,2,7,8,9

console.log(...newArr); // 1 2 7 8 9 // without comma invidually

The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

The spread operator is a bit similar to destructuring. The big difference is the … operator takes all the element from the array and it also doesn’t creates a new variable. and as a consequence, we can only use this where we would otherwise write values separated by a comma.

Copy an array

///copy array
const arr = [1,2,3,4,5]
const copyArr = [...arr]; //copy of arr

copyArr.push(6);
//copyArr becomes 1,2,3,4,5,6
//arr remains unafected

concatenate arrays

let arr = ["a", "b", "c"];
let array = ["d", "e", "f"];

// Append all items from array onto arr
arr = arr.concat(array);

With spread syntax this becomes:

let arr = ["a", "b", "c"];
let array = ["d", "e", "f"];

arr = [...arr, ...array];
// arr is now ["a","b","c","d","e","f"]

I hope you find it useful, let me know your thoughts on this in the comments. If you have any issues or questions about it, feel free to contact me. Thank you 🌟 for reading! like, share and subscribe to my newsletter for more! 💖

🔗Debasish Lenka

Did you find this article valuable?

Support Debasish Lenka by becoming a sponsor. Any amount is appreciated!