Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between push() and unshift() methods in javascript
JavaScript arrays provide two methods for adding elements: push() adds elements at the end, while unshift() adds elements at the beginning. Both methods modify the original array and return the new array length.
push() Method
The push() method adds one or more elements to the end of an array and returns the new length of the array.
let fruits = ['apple', 'mango', 'orange'];
console.log("Original array:", fruits);
let newLength = fruits.push('kiwi');
console.log("After push():", fruits);
console.log("New length:", newLength);
Original array: [ 'apple', 'mango', 'orange' ] After push(): [ 'apple', 'mango', 'orange', 'kiwi' ] New length: 4
unshift() Method
The unshift() method adds one or more elements to the beginning of an array and returns the new length. It shifts all existing elements to higher indexes.
let fruits = ['apple', 'mango', 'orange'];
console.log("Original array:", fruits);
let newLength = fruits.unshift('kiwi');
console.log("After unshift():", fruits);
console.log("New length:", newLength);
Original array: [ 'apple', 'mango', 'orange' ] After unshift(): [ 'kiwi', 'apple', 'mango', 'orange' ] New length: 4
Side-by-Side Comparison
let fruits1 = ['apple', 'mango', 'orange', 'kiwi'];
let fruits2 = ['apple', 'mango', 'orange', 'kiwi'];
console.log("push() returns:", fruits1.push("pineapple"));
console.log("unshift() returns:", fruits2.unshift("pineapple"));
console.log("After push():", fruits1);
console.log("After unshift():", fruits2);
push() returns: 5 unshift() returns: 5 After push(): [ 'apple', 'mango', 'orange', 'kiwi', 'pineapple' ] After unshift(): [ 'pineapple', 'apple', 'mango', 'orange', 'kiwi' ]
Key Differences
| Aspect | push() | unshift() |
|---|---|---|
| Adds elements | At the end | At the beginning |
| Performance | Faster | Slower (shifts all elements) |
| Return value | New array length | New array length |
| Modifies original | Yes | Yes |
Performance Consideration
unshift() is slower than push() because it needs to shift all existing elements to higher indexes when adding elements at the beginning, while push() simply appends to the end.
Conclusion
Use push() to add elements at the end of an array and unshift() to add at the beginning. Both methods modify the original array and return the new length, but push() offers better performance.
