JS: push() Method

The JavaScript <span style="color:#a30000" class="tadv-color">push()</span> method is part of array class. It pushes an element at the end of the array.

Advertisements

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 <span style="color:#a30a00" class="tadv-color">push()</span> method are

  • single element
  • multiple element
  • sub arrays

In this article, we will push the above mentioned elements into an array called <span style="color:#a31400" class="tadv-color">fruits.</span>

Advertisements

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 <span style="color:#a30000" class="tadv-color">push()</span> 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.

Advertisements

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Exit mobile version