JavaScript Reference ยท Array
Array.prototype.concat()
Reference for JavaScript Array.prototype.concat(): merge arrays and values into a new array, shallow copying, Symbol.isConcatSpreadable and the spread alternative.
The concat() method creates a new array containing the elements of the array it is called on, followed by each argument. Array arguments are flattened one level into the result; other values are appended as single elements.
The original arrays are not changed, which makes concat() a non-mutating way to merge arrays. Spread syntax ([...a, ...b]) does the same job and is often preferred today.
[1, 2].concat([3, 4], 5); // [1, 2, 3, 4, 5]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.concat() array.concat(value1) array.concat(value1, value2, /* โฆ */ valueN)
| Name | Description |
|---|---|
value1, โฆ, valueN |
Arrays and/or values to append. Arrays are spread one level; anything else is added as one element. |
Return value: a new array with the elements of array followed by the arguments.
Exceptions: none in normal use. A RangeError occurs if the resulting length would be too large.
Usage notes
- Non-mutating. Unlike
push(), the receiver and the arguments are left unchanged.a.concat()with no arguments is a quick shallow copy. - Only one level of flattening. Arrays nested inside an array argument stay nested, as with
[6, [7]]. Useflat()for deeper flattening. - Shallow copy. Objects inside are shared with the original arrays.
- Array-likes are appended whole unless they have
Symbol.isConcatSpreadableset totrue. An actual array can opt out withfalse. - Strings are values, not spread, so
[].concat("ab")is["ab"]. - Sparse arrays keep their holes.
- concat vs spread:
concat()accepts single values mixed with arrays without extra brackets, while spread works with any iterable (sets, generators). For merging many arrays in a loop,push(...items)into one array avoids repeated copying. - Performance: each call allocates a new array, so building a big array by repeated
concat()in a loop is quadratic. Collect parts and callflat()orconcat()once.
Browser support
Array.prototype.concat() is supported everywhere, including very old browsers.