what are the differences between unshift() and push() methods in javascript?


Both the methods are used to  add elements to the array.But the only difference is unshift() method adds the element at the start of the array whereas push() adds the element at the end of the array.

1) push()

Array.push() method is used to add an element at the end of an array like a queue .In the following example it is shown how to add an element using push() method

 Live Demo

Example

<html>
<body>
<script>
   var cars = ["Benz", "Lamborghini", "Tata safari"];
   cars.push("Ferrari");
   document.write(cars);
</script>
</body>
</html>

Output

Benz,Lamborghini,Tata safari,Ferrari

2)  unshift()

Array.unshift() method is used to add an element at the starting of an array. 

 Live Demo

Example

<html>
<body>
<script>
   var cars = ["Benz", "Lamborghini", "Tata safari"];
   cars.unshift("Ferrari");
   document.write(cars);
</script>
</body>
</html>

Output

Ferrari,Benz,Lamborghini,Tata safari

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements