What is the use of the push() method in JavaScript?

The push() method is a built-in method in JavaScript that allows you to add one or more elements to the end of an array.

The push() method modifies the original array and returns the new length of the array.

The syntax for the push() method is as follows:

array.push(element1, element2, ..., elementN);

Here, array is the name of the array to which you want to add the elements, and element1, element2, …, elementN are the elements you want to add to the end of the array.

For example, consider the following array:

let fruits = ["apple", "banana", "orange"];

To add a new element 'pear' to the end of the fruits array, you can use the push() method as follows:

fruits.push("pear");

After executing this code, the fruits array will be ['apple', 'banana', 'orange', 'pear'], and the push() method will return 4, which is the new length of the array.

You can also add multiple elements to the end of an array using the push() method.

For example:

fruits.push("grape", "pineapple");
console.log(fruits); // ['apple', 'banana', 'orange', 'pear', 'grape', 'pineapple']

Note:

That’s all.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: