Push vs Concat in JavaScript: Key Differences and Usage
push adds one or more elements to the end of an existing array and changes it directly, while concat creates a new array by joining arrays or values without modifying the original. Use push for in-place updates and concat when you want a new combined array.Quick Comparison
Here is a quick side-by-side look at push and concat methods in JavaScript arrays.
| Factor | push | concat |
|---|---|---|
| Modifies original array? | Yes, changes the array in place | No, returns a new array |
| Returns value? | New length of the array | New combined array |
| Can add multiple elements? | Yes, multiple elements can be pushed | Yes, can combine multiple arrays or values |
| Performance | Faster for adding elements to existing array | Slower due to creating new array |
| Use case | When you want to update the original array | When you want to keep original array unchanged |
Key Differences
The push method directly changes the original array by adding new elements to its end. It returns the new length of the array after the elements are added. This means if you have a list of items and want to add more items to it without creating a new list, push is the way to go.
On the other hand, concat does not change the original array. Instead, it creates and returns a new array that combines the original array with the new elements or arrays you provide. This is useful when you want to keep the original array intact and work with a combined copy.
Because push modifies the original array, it is generally faster and uses less memory. concat involves creating a new array, which can be slower and use more memory, but it helps avoid side effects by preserving the original data.
Code Comparison
Using push to add elements to an existing array:
const fruits = ['apple', 'banana']; const newLength = fruits.push('orange', 'mango'); console.log(fruits); console.log(newLength);
concat Equivalent
Using concat to add elements without changing the original array:
const fruits = ['apple', 'banana']; const newFruits = fruits.concat('orange', 'mango'); console.log(fruits); console.log(newFruits);
When to Use Which
Choose push when you want to add elements directly to an existing array and don't need to keep the original unchanged. It is efficient and simple for in-place updates.
Choose concat when you want to combine arrays or values but keep the original array intact. This is important when you want to avoid side effects or work with immutable data patterns.
Key Takeaways
push modifies the original array and returns its new length.concat returns a new combined array without changing the original.push for in-place updates and better performance.concat to keep original arrays unchanged and avoid side effects.