JS: push() Method

The JavaScript push() method is part of array class. It pushes an element at the end of the array.

It is possible to push more than one element at the same time using this method.

The types of items that you can push using push() method are

  • single element
  • multiple element
  • sub arrays

In this article, we will push the above mentioned elements into an array called fruits.

Push Single Element

<script>
  var fruits = ['apple','orange'];
fruits.push('banana');
console.log(fruits);
//output = ['apple','orange','banana']
</script>

Push Multiple Elements

You can push more than one elements into the array using push() method.

<script>
  var fruits = ['apple','orange'];
fruits.push('banana','grapes','mango');
console.log(fruits);
//output = ['apple','orange','banana','grapes','mango']
</script>

Push a sub-array

When you push a sub-array into a JavaScript array, a two-dimensional array is created.

<script>
  var fruits = ['apple','orange'];
fruits.push('banana',['plums','mango']);
console.log(fruits);
//output = ['apple','orange','banana',['plums','mango']]
</script>

The sub-array is indicated using another square bracket.

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag