- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
- Related Articles
- Difference between push() and unshift() methods in javascript
- what are the differences between unshift() and push() methods in javascript?
- Push vs pop in stack class in C#
- Validating push pop sequence in JavaScript
- Push specific elements to last in JavaScript
- Creating an associative array in JavaScript with push()?
- JavaScript to push value in empty index in array
- d vs D in JavaScript?
- Window.onload vs onDocumentReady in javascript
- Undeclared vs Undefined? In JavaScript
- innerHTML vs innerText in JavaScript.
- Arrays vs Set in JavaScript.
- Const vs Let in JavaScript.
- w vs W in JavaScript regex?
- Shift() vs pop() methods in JavaScript?

Advertisements