JavaScript Unshift() method is very much similar to the push() method but the difference is that the unshift() method adds the elements at the very beginning of the array whereas the push() method adds at the end of the array.
Javascript Array unshift() method: The JavaScript Array unshift() Method is used to add one or more elements to the beginning of the given array. This function increases the length of the existing array by the number of elements added to the array.
Syntax:
array.unshift(element1, element2, ..., elementX)
Example: Below is the example of the Array unshift() method.
Javascript
<script>
function func() {
var array = [ "GFG" , "Geeks" , "for" , "Geeks" ];
var value = array.unshift( "GeeksforGeeks" );
console.log(value);
console.log(array);
}
func();
</script>
|
Output:
GeeksforGeeks,GFG,Geeks,for,Geeks.
Javascript Array push() method: The JavaScript Array push() Method is used to add one or more values to the end of the array. This method changes the length of the array by the number of elements added to the array.
Syntax:
arr.push(element1, elements2 ....., elementN]])
Example: Below is the example of the Array push() method.
Javascript
<script>
function func() {
var arr = [ 'GFG' , 'gfg' , 'g4g' ];
arr.push( 'GeeksforGeeks' );
console.log(arr);
}
func();
</script>
|
Output:
GFG,gfg,g4g,GeeksforGeeks
Difference Table:
Javascript Array unshift() method | Javascript Array push() method |
---|
This method adds an elements to the beginning of the array. | This method adds elements to the end of the array. |
This method shifts the index of the first element by 1. | This method adds a new index at the last of the array. |