Array Spread
The spread syntax (...) isn’t limited to merging object properties; it is highly effective when working with arrays as well.
Merging Arrays
The spread syntax expands the elements of an existing array into individual elements, making it incredibly easy to merge arrays or insert an entire array inside another one.
const oldNums = [1, 2, 3];
// We spread oldNums directly into the middle of a new array
const newNums = [...oldNums, 4, 5, 6];
console.log(newNums);
// Output: [1, 2, 3, 4, 5, 6]
Practical Example
Instead of relying on loops or .push() calls to combine batches of data, the spread operator allows you to merge datasets in a single, readable line.
function mergeBatches(oldBatch, newBatch) {
// Returns a brand new array combining both
return [...oldBatch, ...newBatch];
}
const batchA = ["Msg1", "Msg2"];
const batchB = ["Msg3", "Msg4"];
const fullLog = mergeBatches(batchA, batchB);
console.log(fullLog);
// Output: ["Msg1", "Msg2", "Msg3", "Msg4"]