In JavaScript, the 'concat()' method is used to merge two or more arrays together, creating a new array that contains elements from all the arrays involved. The original arrays remain unchanged.
Syntax:
array.concat(array1, array2, ..., arrayN)
- array: The array to which other arrays will be concatenated.
- array1, array2, ..., arrayN: Arrays to be concatenated with the original array.
Example:
let fruits1 = ['apple', 'banana'];
let fruits2 = ['orange', 'grape'];
let allFruits = fruits1.concat(fruits2);
console.log(allFruits); // Output: ['apple', 'banana', 'orange', 'grape']
Explanation:
- In the example, 'concat(fruits2)' merges 'fruits2' array with 'fruits1' array, creating a new array 'allFruits' that contains elements from both arrays.
- The 'concat()' method does not modify the original arrays ('fruits1' and 'fruits2'), it returns a new array containing the concatenated elements.
The 'concat()' method provides a convenient way to combine arrays without modifying the original arrays, making it useful for array manipulation and data restructuring in JavaScript.