• JavaScript Video Tutorials

JavaScript - Array push() Method



The JavaScript Array push() method is used to append one or more elements to the end of an array and returns the new length of the array. This method changes the length of the original array and returns a new length after insertion. For Example, myArr.push('x', 'y') adds 'x' and 'y' to the end of myArr.

If we want to add element(s) to the beginning of the array, use the JavaScript Array.unshift() method.

Syntax

Following is the syntax of JavaScript Array push() method −

array.push(value1, value2, value3, ..., valueN);

Parameters

This method accepts only one parameter. The same is described below −

  • value1…valueN − These are the values that will be added to the right end of the array.

Return value

This method modifies the original array by appending one or more elements to the end. It returns the updated length of the array.

Examples

Example 1

In the following example, we are using the JavaScript Array push() function to add an element to the end of the array.

<html>
<body>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant"];
      animals.push("Dinosaur");
      document.write(animals);
   </script>
</body>
</html>

If we execute the above program, the new element will be added to the end of the array.

Output

Lion,Cheetah,Tiger,Elephant,Dinosaur

Example 2

Here, we are pushing three elements to the end of the array. Also, we are checking the length of the array after inserting the new elements −

<html>
<body>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant"];
      const count = animals.push("Dinosaur", "Leopard", "Hippopotamus");
      document.getElementById("demo1").innerHTML = animals;
      document.getElementById("demo2").innerHTML = count;
   </script>
</body>
</html>

As we can see in the output, the elements has been added to the array and length is also increased to 7 from 4.

Advertisements