In Javascript, the concat()
method is an array function that is used to merge arrays, and therefore create a new one after merging.
You can merge more than two arrays using this method. A new array is returned that contains all the arrays merged as one.
It can also be used to merge ordinary values into arrays.
// just arrays
array.concat(array1, array2, array3, ..., arrayN)
// values
array.concat(value1, value2, ..., valueN)
array
: This is the array that needs to be concatenated with other arrays or values.
array1...arrayN
: This represents any number of arrays you want to concatenate with array
.
value1...valueN
: This represents any number of values to concatenate with array
.
The value returned is a new array that contains all the passed parameters with the array
that is originally called the concat()
method.
In the example below, arrays are created and merged with other arrays and values. And then the merged arrays are logged to the console.
// create new arrayslet array1 = [1, 2, 3];let array2 = ["a", "b", "c"]let array3 = ["Javascript", "Ruby", "Python"]let array4 = []// create merge arrayslet mergedArray1 = array1.concat(4,5,6)let mergedArray2 = array2.concat("d", "e", ["f", "g", "h"]);let mergedArray3 = array3.concat(["Java", "C++", "GoLang"], "Solidity")let mergedArray4 = array4.concat(array1, array2, array3);// log merged arraysconsole.log(mergedArray1)console.log(mergedArray2)console.log(mergedArray3)console.log(mergedArray4)
The
concat()
method does not change the existing arrays.