Push object to end of the array

Push Object to End of the Array

Arrays are one of the most crucial data structures in JavaScript. They are used to store a collection of related values. The array is a data structure that is used to store a collection of related values. In JavaScript, arrays can contain any data type, including objects.

Using push() Method

The easiest way to add an object to the end of an array is by using the push() method. The push method adds one or more elements to the end of an array and returns the new length of the array. It mutates the original array.


let myArray = [1, 2, 3, 4];
myArray.push(5);
console.log(myArray); // Output: [1, 2, 3, 4, 5]

let myObject = { name: "John", age: 30 };
myArray.push(myObject);
console.log(myArray); // Output: [1, 2, 3, 4, { name: "John", age: 30 }]

The above code demonstrates how to add an object to the end of an array using the push() method. We create an array with some values and then add one more value using the push() method.

Using Spread Syntax

The spread syntax is a more concise way to add an object to the end of an array. The spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments for function calls or elements for array literals are expected.


let myArray = [1, 2, 3, 4];
let myObject = { name: "John", age: 30 };
myArray = [...myArray, myObject];
console.log(myArray); // Output: [1, 2, 3, 4, { name: "John", age: 30 }]

The above code demonstrates how to add an object to the end of an array using the spread syntax. We create an array with some values and then use the spread syntax to add an object to the end of the array.

Using Concat() Method

The concat() method is used to merge two or more arrays. The method does not change the existing arrays but instead returns a new array that contains all elements from the original arrays. We can use this method to add an object to the end of an array.


let myArray = [1, 2, 3, 4];
let myObject = { name: "John", age: 30 };
myArray = myArray.concat(myObject);
console.log(myArray); // Output: [1, 2, 3, 4, { name: "John", age: 30 }]

The above code demonstrates how to add an object to the end of an array using the concat() method. We create an array with some values and then use the concat() method to add an object to the end of the array.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe