JavaScript Array concat() method
The concat()
method in JavaScript is used to merge two or more arrays. It creates and returns a new array that consists of the elements from the original array(s) combined with the additional arrays or values passed as arguments. The original arrays are not modified by the concat()
method.
Syntax:
array1, array2, ..., arrayN
: The arrays (or values) you want to concatenate to the original array.
Return Value:
- A new array consisting of the elements from the original array combined with the elements from the arrays or values passed as arguments.
Key Points:
- Does not modify the original array:
concat()
returns a new array and leaves the original array unchanged. - Can concatenate multiple arrays: You can pass multiple arrays (or values) to concatenate them in sequence.
- Works with non-array values: You can also pass individual values to concatenate them with the array.
Example 1: Concatenating two arrays
Example 2: Concatenating multiple arrays
Example 3: Concatenating arrays with non-array values
Example 4: Concatenating nested arrays
Note: In this example, if you concatenate nested arrays, they are not flattened. The inner arrays are added as elements to the new array.
Example 5: Concatenating with an empty array
Summary:
concat()
creates a new array by merging the original array with other arrays or values. It does not modify the original array but returns a new array with combined elements. You can use it to concatenate multiple arrays or values in one call.