- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
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
Advertisements