Open In App

Add an Object to an Array in JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In this article, we will learn about how to add an object to an array in JavaScript. There are 3 popular methods that can be used to insert or add an object to an array.

Method 1: Using JavaScript Array push() Method

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array. 

Syntax:

array.push(objectName)

Example: In this example, we will use the push() method to add an object to the array in JavaScript.

Javascript




function pushFunction() {
    list.push("Four", "Five"
    );
    console.log(list);
}
 
// Diver Code
let list = ["One", "Two", "Three"];
pushFunction();


Output

[ 'One', 'Two', 'Three', 'Four', 'Five' ]

Method 2: Using JavaScript Array splice() Method

The splice method is used to both remove and add elements from a specific index. An object can only be added without deleting any other element by specifying the second parameter to 0. 

Syntax:

arr.splice(index, 0, objectName)

Example: In this example, we will add new objects to the array using the splice() method in Javascript.

Javascript




function spliceFunction() {
    list.splice(2, 0, "Angular", "SQL");
    console.log(list);
}
 
// Driver Code
let list = ["HTML", "CSS", "JavaScript"];
spliceFunction();


Output

[ 'HTML', 'CSS', 'Angular', 'SQL', 'JavaScript' ]

Method 3: Using JavaScript Array unshift() Method

The unshift() method is used to add one or multiple elements to the beginning of an array. It returns the length of the new array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the beginning of the array. 

Syntax:

arr.unshift( object );

Example: In this example, we will be adding new objects in the array using the unshift() method in JavaScript.

Javascript




function unshiftFunction() {
    list.unshift("for", "Geeks",);
    console.log(list);
}
 
// Diver Code
let list = ["Geeks", "Contribute", "Explore"];
 
unshiftFunction();


Output

[ 'for', 'Geeks', 'Geeks', 'Contribute', 'Explore' ]

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Last Updated : 28 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads