concat() function returns a new array that consists of the two given arrays together.
const array = [1, 2, 3]; const array2 = [4, 5, 6]; const array3 = array.concat(array2); // [1, 2, 3, 4, 5, 6] array3 === array; // false
push() with spread operator
You can also use the
push() method with the spread operator.
This approach modifies the array in place instead of creating a new array.
const array = [1, 2, 3]; const array2 = [4, 5, 6]; array.push(...array2); // [1, 2, 3, 4, 5, 6]
Note: Be careful about using this approach with potentially huge arrays. This can cause a stack overflow error if
array2 is massive.
const array = ; const array2 = Array(10_000_000).fill(null); // RangeError: Maximum call stack size exceeded array.push(...array2);
Using Immutable Patterns
You can also use the spread operator as an alternative to
concat() to create a new array as follows.
This approach is syntactically neater, and gives you more flexibility in constructing the new array.
const array = [1, 2, 3]; const array2 = [4, 5, 6]; const array3 = [...array, ...array2]; // [1, 2, 3, 4, 5, 6]
More Fundamentals Tutorials
- Variables: Variables are used to store data. They are declared using the
- Operators: Operators are used to perform operations on data.
- Control flow statements: Control flow statements allow you to control the order in which your code is executed.
- Functions: Functions are blocks of code that can be reused.
- Objects: Objects are used to store data in key-value pairs.
- Arrays: Arrays are used to store data in a sequential order.
- Events and event handlers: Events are notifications that are sent by the browser when something happens, such as when the user clicks on an element or moves the mouse over an element. Event handlers are functions that are called in response to an event.
I hope this helps!