How to Use concat in JavaScript: Syntax and Examples
In JavaScript,
concat is a method used to join two or more arrays or strings into a new array or string without changing the original ones. You call it on an array or string and pass the items you want to add as arguments, like array1.concat(array2) or string1.concat(string2).Syntax
The concat method can be used with arrays or strings. It creates a new array or string by joining the original with the provided values.
- For arrays:
array1.concat(array2, array3, ...) - For strings:
string1.concat(string2, string3, ...)
This method does not change the original array or string but returns a new one.
javascript
const newArray = array1.concat(array2); const newString = string1.concat(string2);
Example
This example shows how to join two arrays and two strings using concat. It demonstrates that the original arrays and strings stay the same, and a new combined result is returned.
javascript
const fruits = ['apple', 'banana']; const moreFruits = ['orange', 'grape']; const allFruits = fruits.concat(moreFruits); const greeting = 'Hello, '; const name = 'Alice!'; const message = greeting.concat(name); console.log('Original fruits:', fruits); console.log('All fruits:', allFruits); console.log('Greeting message:', message);
Output
Original fruits: [ 'apple', 'banana' ]
All fruits: [ 'apple', 'banana', 'orange', 'grape' ]
Greeting message: Hello, Alice!
Common Pitfalls
One common mistake is expecting concat to change the original array or string. It does not modify them but returns a new combined value. Another pitfall is using concat with non-array or non-string types, which can cause unexpected results.
Also, when concatenating arrays, concat only adds the elements; it does not flatten nested arrays.
javascript
const arr1 = [1, 2]; const arr2 = [3, 4]; // Wrong: expecting arr1 to change arr1.concat(arr2); console.log(arr1); // Still [1, 2] // Right: assign the result const combined = arr1.concat(arr2); console.log(combined); // [1, 2, 3, 4]
Output
[1, 2]
[1, 2, 3, 4]
Quick Reference
| Usage | Description | Example |
|---|---|---|
| Array concat | Joins arrays into a new array | [1,2].concat([3,4]) → [1,2,3,4] |
| String concat | Joins strings into a new string | 'Hi'.concat(' there') → 'Hi there' |
| Non-destructive | Original arrays/strings stay unchanged | a.concat(b) does not change a |
| Multiple arguments | Can join many arrays/strings at once | a.concat(b, c, d) |
Key Takeaways
Use
concat to join arrays or strings without changing the originals.concat returns a new combined array or string.Remember to assign the result to a variable to keep the joined value.
concat can take multiple arguments to join many items at once.It does not flatten nested arrays when joining arrays.