The concat() method returns a new array by merging two or more values/arrays.
Example
concat() Syntax
The syntax of the concat() method is:
arr.concat(value1, value2, ..., valueN)
Here, arr is an array.
concat() Parameters
The concat() method takes in an arbitrary number of arrays and/or values as arguments.
concat() Return Value
- Returns a newly created array after merging all arrays/values passed in the argument.
The concat() method first creates a new array with the elements of the object on which the method is called. It then sequentially adds arguments or the elements of arguments (for arrays).
Example 1: Using concat() method
Output
[ 'JavaScript', 'Python', 'Java', 'C', 'C++' ] [ 'C', 'C++', 'Lua', 'JavaScript', 'Python', 'Java' ]
Example 2: Concatenating nested arrays
The concat() method returns the shallow copy of the concatenated elements in the following way:
- It copies object references to the new array. (For example: passing a nested array) So if the referenced object is modified, the changes are visible in the returned new array.
- It copies the value of strings and numbers to the new array.
Output
[ 1, 2, 3, [ 4, 5 ], [ 6, 7 ] ] [ 0, 2, 3 ] [ 1, 2, 3, [ 4, 5 ], [ 6, 7 ] ] [ [ 1, 2, 3 ], [ 6, 7 ] ] [ 1, 2, 3, [ 4, 5, 6 ], [ 6, 7 ] ]
Here, the nested array's reference is copied to the concatenated array. So, when we modify any of the references, the changes are reflected everywhere.
Recommended Readings: