the future of the web is collaborative and creative,
therefore it must be secure, inclusive, and accessible.

the future is now.

Array.concat() vs Spread Operator to Concatenate Arrays

by Tim Combs | May 27, 2020

Tags: array javascript concat spread_operator tips_N_tricks

I follow @getify on Twitter because he posts interesting code tips & tricks. And you all know how much I love to share code tips & tricks. He also publishes the You Don't Know JS book series, a great deep dive into the core mechanisms of the JavaScript language.

Recently, he tweeted about use cases for Array.concat() vs the spread operator when concatenating arrays. As always, when I hear, read, see a cool tip or trick I like to play around with it to lock the concept down.

let arr1 = [3, 5, 6, 2, 3, 6];
let arr2 = [5, 46, 2, 'r', 'e'];
let item1 = 'item1';

let spreadJoiner = [item1, ...arr1, ...arr2];
let concatChain = [].concat(item1).concat(arr1).concat(arr2);
let concatArgs = [].concat(item1, arr1, arr2);

// all three give equivalent results
// ['item1', 3, 5, 6, 2, 3, 6, 5, 46, 2, 'r', 'e']
console.log('spread', spreadJoiner);
console.log('concatChain', concatChain);
console.log('concatArgs', concatArgs);

As you can see, the above code gives 3 equivalent ways to concatenate arrays. The spread operator ... often increases readability, however, when you need to concatenate arrays and non-arrays into a new array one has to be declarative. [].concat() allows for chaining and handles both non-arrays and arrays much easier so one can iterate over a collection of objects.

All ways work because we can hard code the objects for concatenation, but what if you don't know the number or types of objects you need to concatenate into an array?

const anArray = ['tree', 4, 6, 'fish', [1, 5, 8, 'a word'], ['anotherArr', 5, 9, {tree: 'yep', fish: 'nope'}], [1, 3, 5]];

let arr = [].concat(...array);

/* arr is: 
['tree', 4, 6, 'fish', 1, 5, 8, 'a word', 'anotherArr', 5, 9, {'tree': 'yep', 'fish': 'nope'}, 1, 3, 5]

The objects are concatenated nicely.

Using [].concat() and passing it an array of any objects with the spread operator concatenates them all. Again, You don't have to worry about what type of object that is passed in, it concatenates the objects smoothly and automatically.

const anArray = ['tree', 4, 6, 'fish', [1, 5, 8, 'a word'], ['anotherArr', 5, 9, {tree: 'yep', fish: 'nope'}], [1, 3, 5]];

let arr = [...array];

/* arr is a shallow copy of the array that was passed in, so: 
['tree', 4, 6, 'fish', [1, 5, 8, 'a word'], ['anotherArr', 5, 9, {tree: 'yep', fish: 'nope'}], [1, 3, 5]]

This is a good trick in itself if you need a copy of an array,
but it doesn't concatenate the objects

Tags: array javascript concat spread_operator tips_N_tricks