JavaScriptArrays
Array. prototype. concat()
Combines arrays and values into a new array.
- Returns
- A new, combined array.
- Changes the original
- No
Example
#JavaScript
const frontend = ['HTML', 'CSS']
const backend = ['Node.js', 'SQL']
console.log(frontend.concat(backend, 'Git'))
console.log([...frontend, ...backend])
console.log(frontend)Console
['HTML', 'CSS', 'Node.js', 'SQL', 'Git']
['HTML', 'CSS', 'Node.js', 'SQL']
['HTML', 'CSS']
Definition and usage
#The concat() method builds a new array made up of the current array’s elements plus the given arguments. Arrays passed as arguments are spread out into elements (one level deep), while plain values are appended as they are.
The original arrays don’t change. In modern code the same effect is often achieved with the spread syntax: [...a, ...b].
The merge is shallow: the objects in the new array are the same objects as in the originals.
Syntax
#Syntax
array.concat(value1, value2, …)Parameters
#value1…valueN
arrays or values
The elements to append. Arrays are spread one level deep.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- The
[...a, ...b]syntax is more common today, butconcat()can be clearer with many arguments. - Arrays nested deeper than one level aren’t spread out. Use
flat()for that.
Related entries
#- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
- Array.prototype.push()Adds elements to the end of an array and returns its new length.
- Array.prototype.flat()Flattens nested arrays down to the given depth.
- Array.prototype.slice()Returns a copy of part of an array without changing the original.
Spotted a mistake or missing an example? Write to us.