Question:
I’m working with arrays of objects in JavaScript and exploring methods to add new elements. I’ve encountered the push() and concat() methods, both of which seem to be used for adding elements to an array. However, I’m not entirely clear on the main difference between these two methods.
Here are the examples I’ve tried:
Example 1 (using push()):
let people = [
{ name: "John", age: [30, 40], city: "New York" },
{ name: "Alice", age: [30, 40], city: "Los Angeles" },
{ name: "Bob", age: [30, 40], city: "Chicago" },
{ name: "Eva", age: [30, 60], city: "San Francisco" },
{ name: "David", age: [30, 50], city: "Miami" }
];
// Create a new person object
const newPerson = { name: "Frank", age: [25, 35], city: "Seattle" };
// Add the new person to the 'people' array using push()
people.push(newPerson);
console.log(people);
Example 2 (using concat()):
let people = [
{ name: "John", age: [30, 40], city: "New York" },
{ name: "Alice", age: [30, 40], city: "Los Angeles" },
{ name: "Bob", age: [30, 40], city: "Chicago" },
{ name: "Eva", age: [30, 60], city: "San Francisco" },
{ name: "David", age: [30, 50], city: "Miami" }
];
const newPerson = { name: "Frank", age: [25, 35], city: "Seattle" };
people = people.concat(newPerson);
console.log(people);
Could someone please clarify the primary distinction between push() and concat() when it comes to adding elements to an array in JavaScript?
2
Answers
These are the differences:
push()
modifies the original array.concat()
doesn’t modify the original array, it returns a new array by making a shallow copy of the original array.concat()
is an array, it’s merged with the original array (like[...arr1, ...arr2]
).push()
always adds the argument as a single element — if it’s an array, it becomes a nested array. E.g. comparearr1.concat(arr2)
witharr1.push(arr2)
.push()
returns the length of the updated array,concat()
returns the new array.concat()
creates a new array by merging the array the method is called on with all arguments flattened (1 level deep) into an array.push()
just adds elements to an existing array.Since
concat()
creates a new array avoid it if you use a repetitive task like filling an array with values from another array, it’s extremely slow: