Push() vs unshift() in JavaScript?



push() vs unshift()

The methods push() and unshift() are used to add an element in an array. But they have a slight variation. The method push() is used to add an element at the end of the array, whereas the method unshift() is used to add the element at the start of the array. Let's discuss them in detail.

push()

syntax

array.push("element");

Example

In the following example, to a 3 element array, using push() method another element is added at the back of the array and the result is displayed in the output.

<html>
<body>
<script>
   var companies = ["Spacex", "Hyperloop", "Solarcity"];
   document.write("Before push:" +" "+ companies);
   companies.push("Tesla");
   document.write("</br>");
   document.write("After push:" +" "+ companies);
</body>
</html>

Output

Before push: Spacex,Hyperloop,Solarcity
After push: Spacex,Hyperloop,Solarcity,Tesla

unshift()

syntax

array.unshift("element");

Example

In the following example, to a 3 element array, using unshift() method another element is added at the start of the array and the result is displayed in the output.

<html>
<body>
<script>
   var companies = ["Spacex", "Hyperloop", "Solarcity"];
   document.write("Before unshift:" +" "+ companies);
   companies.unshift("Tesla");
   document.write("</br>");
   document.write("After unshift:" +" "+ companies);
</script>
</body>
</html>

Output

Before unshift: Spacex,Hyperloop,Solarcity
After unshift: Tesla,Spacex,Hyperloop,Solarcity
raja
Published on 19-Aug-2019 13:58:49
Advertisements