concat
method does not change the existing array:const shapes = ['Triangle', 'Square'];shapes.concat(['Circle', 'Rectangle']); // ['Triangle', 'Square', 'Circle', 'Rectangle']shapes; // ['Triangle', 'Square']
push
method on the other hand modifies the original array.const animals = ['cat', 'dog', 'mouse'];animals.push('bird', 'cow'); // 5animals; // ['cat', 'dog', 'mouse', 'bird', 'cow']
concat
returns a new array while push
returns the length of updated array.concat
creates a new array to hold the result of merged arrays, it's slower than push
.push
.concat
.source
to dest
by splitting the source array into multiple chunks and copying them one by one.const MAX_BLOCK_SIZE = 65535; // max parameter array size for use in Webkitexport function appendArrayInPlace<T>(dest: T[], source: T[]) {let offset = 0;let itemsLeft = source.length;if (itemsLeft <= MAX_BLOCK_SIZE) {dest.push.apply(dest, source);} else {while (itemsLeft > 0) {const pushCount = Math.min(MAX_BLOCK_SIZE, itemsLeft);const subSource = source.slice(offset, offset + pushCount);dest.push.apply(dest, subSource);itemsLeft -= pushCount;offset += pushCount;}}return dest;}
const a = [1, 2, 3];const b = [4, 5, 6];const c = [7, 8, 9];const final = [...a, ...b, ...c]; // [1, 2, 3, 4, 5, 6, 7, 8, 9]
push
method as well:const a = [1, 2, 3];const b = [4, 5, 6];a.push(...b);a; // [1, 2, 3, 4, 5, 6]
Array.prototype.push.apply(firstArray, secondArray)
is another option that also works in ES5. This approach however isn't recommended in case the second array is very large because the maximum number of parameters in one function is limited.push
is faster than concat
.