Array Concat Method
concat() returns a new array made of the array it is called on followed by its arguments. Neither the original array nor the arguments are changed.
const fruit = ['apples', 'pears'];const veg = ['carrots', 'leeks'];
const shopping = fruit.concat(veg);
console.log(shopping);console.log(fruit);This prints:
[ 'apples', 'pears', 'carrots', 'leeks' ][ 'apples', 'pears' ]Several arguments, and single values
Section titled “Several arguments, and single values”concat() accepts any number of arguments. An argument that is an array has its elements added one by one, and any other value is added as a single element. Only the top level of an array argument is unpacked, so an array nested inside it stays an array.
const list = [1, 2];
console.log(list.concat(3, [4, 5], [[6, 7]]));This prints:
[ 1, 2, 3, 4, 5, [ 6, 7 ] ]To flatten deeper nesting, use flat().
The spread syntax
Section titled “The spread syntax”The spread syntax ... does the same job inside an array literal, and many people find it easier to read. Either way the result is a shallow copy, which means objects in the arrays are shared rather than copied, so a change to one of them shows through both arrays.
const morning = [{ task: 'Emails' }];const afternoon = [{ task: 'Meetings' }];
const day = [...morning, ...afternoon];day[0].task = 'Inbox zero';
console.log(day);console.log(morning);This prints:
[ { task: 'Inbox zero' }, { task: 'Meetings' } ][ { task: 'Inbox zero' } ]To copy the objects as well, use structuredClone(). Deep vs Shallow Copy has more on the difference.
Steve Griffith covers this topic in his video JavaScript Array concat method.