Concat is a fundamental JavaScript method used to merge arrays or strings, returning new collections without modifying the originals. Understanding concat is essential for data manipulation in modern web applications, particularly when working with React, Next.js, and other frameworks where immutable data patterns are preferred.
The concat method has been a cornerstone of JavaScript since its early days and remains widely supported across all modern browsers, making it a reliable choice for production applications. Combined with other JavaScript array methods like map() and filter(), concat forms the foundation of functional programming in JavaScript.
Unlike methods that mutate arrays in place, concat always returns a new array, making your code more predictable and easier to reason about.
Key benefits of using concat in your JavaScript applications
Immutable Data Transformations
Concat creates new arrays rather than mutating existing ones, preventing unexpected side effects in your applications.
Multiple Array Support
Merge three or more arrays in a single call without method chaining.
Mixed Type Handling
Combine arrays with primitive values seamlessly in one operation.
Wide Browser Support
Available across all modern browsers since 2015, requiring no polyfills.
Array.prototype.concat() Basics
The concat() method of Array instances is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. As documented by MDN Web Docs, concat has been a reliable part of JavaScript since its early days.
Syntax
array.concat(value1, value2, /* ..., */ valueN)
The concat method accepts multiple arguments, where each argument can be:
- An array whose elements will be added to the new array
- A value (string, number, object) that will be added as a single element
- Multiple arguments can be passed, and they are concatenated in order
Return Value
The method returns a new Array instance containing the elements of the original array followed by the elements of each argument. If no arguments are provided, concat returns a shallow copy of the original array.
This behavior differs from methods like innerHTML which modify the DOM directly--concat operates purely on data, leaving your original arrays untouched.
1const array1 = ['a', 'b', 'c'];2const array2 = ['d', 'e', 'f'];3const array3 = array1.concat(array2);4 5console.log(array3);6// Expected output: ['a', 'b', 'c', 'd', 'e', 'f']Concatenating Multiple Arrays
One of concat's powerful features is its ability to merge multiple arrays in a single call, reducing the need for method chaining and improving code readability.
Combining Three or More Arrays
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
const numbers = num1.concat(num2, num3);
console.log(numbers);
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
This pattern is particularly useful when you need to aggregate data from multiple sources, such as combining results from different API endpoints or merging configuration arrays in your application. Whether you're building a React application or a Next.js project, this approach keeps your code clean and predictable.
Mixing Arrays and Values
The concat method also allows you to mix arrays and primitive values in a single call:
const letters = ['a', 'b', 'c'];
const alphaNumeric = letters.concat(1, [2, 3]);
console.log(alphaNumeric);
// Output: ['a', 'b', 'c', 1, 2, 3]
In this example, the number 1 is added as a single element, while the array [2, 3] has its elements spread into the result. This flexibility makes concat particularly powerful when working with dynamic data from APIs.
Deep vs Shallow Copying
Understanding the difference between deep and shallow copying is crucial when working with concat, especially with nested data structures.
Shallow Copy Behavior
The concat method creates a shallow copy, meaning that for nested arrays or objects, the references are copied rather than the values themselves:
const num1 = [[1]];
const num2 = [2, [3]];
const numbers = num1.concat(num2);
console.log(numbers);
// Output: [[1], 2, [3]]
// Modifying the original array affects the concatenated result
num1[0].push(4);
console.log(numbers);
// Output: [[1, 4], 2, [3]]
This behavior is important to consider when working with complex data structures, as modifications to the original nested arrays will be reflected in the concatenated result. When building enterprise JavaScript applications, understanding this behavior helps prevent subtle bugs that can be difficult to trace.
When to Use Deep Copy
For scenarios requiring complete independence between the original and concatenated arrays, you may need to implement deep copying strategies. This is particularly relevant when dealing with state management in React applications, where unexpected mutations can lead to difficult-to-debug issues. When working with complex JavaScript objects, consider using structured cloning or libraries like Lodash's cloneDeep() function.
Understanding shallow vs deep copying is also essential when working with template strings and other JavaScript data manipulation techniques.
String.prototype.concat() for Comparison
JavaScript also provides a concat() method for strings, which serves a similar purpose of joining values together.
String Concatenation Syntax
const str1 = 'Hello';
const str2 = ' ';
const str3 = 'World';
const result = str1.concat(str2, str3);
console.log(result);
// Output: 'Hello World'
While string concatenation with + or template literals is often preferred for readability, the concat method provides an alternative approach that some developers find more intuitive for complex concatenation scenarios.
This mirrors the behavior of array concat--rather than modifying the original string, concat returns a new string with the concatenated values. Understanding this pattern helps when working with string manipulation in JavaScript.
XPath concat() Function
Beyond JavaScript, the concat concept appears in other technologies, including XPath for XML processing.
XPath concat Syntax
The XPath concat function concatenates two or more strings and returns the resulting string:
concat(string1, string2 [,stringN]*)
This function is part of the XPath 1.0 specification and is widely supported across XML processors and browsers. As documented by MDN Web Docs on XPath concat, this function has been a standard part of XML processing for decades.
XPath concat Example
concat('Hello', ' ', 'World')
<!-- Result: 'Hello World' -->
This function is commonly used in XSLT transformations and XPath expressions for generating dynamic string values in XML documents.
Frequently Asked Questions
Does concat modify the original array?
No, concat does not modify the original array. It returns a new array containing all elements from the original array and the concatenated arguments.
Can concat handle nested arrays?
Yes, but with a caveat. Concat performs a shallow copy of nested arrays, meaning the nested arrays share references with the original. Changes to nested arrays will affect both the original and concatenated result.
How many arrays can I concatenate at once?
There's no specific limit--you can pass as many arrays or values as you need to concat, and all will be merged into a single new array.
Should I use concat or the spread operator?
Both approaches work well. Concat is slightly more explicit about merging arrays, while the spread operator offers more modern syntax. Choose based on your codebase conventions and readability preferences.
Common Use Cases in Web Development
Data Aggregation
When building dashboards or data visualization components, concat is invaluable for combining datasets from multiple sources:
const initialData = [{ id: 1, value: 100 }];
const newData = [{ id: 2, value: 200 }];
const updatedData = initialData.concat(newData);
State Management
In React state updates, concat provides an immutable way to add items to arrays:
const [items, setItems] = useState([]);
const addItem = (newItem) => {
setItems(prevItems => prevItems.concat(newItem));
};
This pattern is essential for proper React state management and ensures predictable updates that trigger re-renders correctly.
API Response Handling
When combining paginated API results, concat offers a clean approach:
const firstPage = await fetchAPI('/items?page=1');
const secondPage = await fetchAPI('/items?page=2');
const allItems = firstPage.concat(secondPage);
For more complex scenarios involving HTTP requests, concat helps maintain clean, functional data transformation pipelines.
Sources
- MDN Web Docs - Array.prototype.concat() - Official JavaScript reference for the concat method
- MDN Web Docs - XPath concat Function - XPath specification for string concatenation
- W3Schools - JavaScript Array concat() - Beginner-friendly tutorials with practical examples