How to add an object to an array in JavaScript?

There can be a situation where you want to insert or add an object to an array. In JavaScript there are three popular methods which can be used to insert or add an object to an array.

push()
splice()
unshift()

push(): This method is used to add one or multiple elements to an array. Elements are added to the end of an array and it returns the new length of the newly generated array. In this method an object can be inserted by passing the object as a parameter and the object is always added to the end of the array.

Syntax:
array.push(object);

Example:

Output:
[“Apple”, “Banana”, “Grapes”, “Mango”]

splice(): Splice method can be used to add and remove an element from an array from a specific index. It accepts three parameters, starting index, number of elements to delete and items to be added to the array. If you pass number of elements to be zero then this method will add the object to the array.

You need to pass the object to the method to be added and also the index where you want to insert the element. That means this method inserts the object at the specified index.

Syntax:
arr.splice(index, 0, object);

Example:

Output:
[“Apple”, “Banana”, “Grapes”, “Mango”]

unshift(): This method is used to insert one or multiple elements at the beginning of an array and returns the length of the newly created array. New element can be inserted by passing it as a parameter to this method. Element is always added to the beginning of the array by using this method.

Syntax:
arr.unshift(object);

Example:

Output:
[“Mango”, “Apple”, “Banana”, “Grapes”]

So this is how you can add an element to an array by using these simple methods available in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *