Push | pop | shift | unshift | Array Methods

push, pop, shift & unshift are the Array Methods which are mostly used while programming in javaScript.

push :point_right: Using push( ) we can add elements to the end of an array.

let arr = [ 1, 2, 3 ];
arr.push(4); // pushing 4 in end of array
console.log(arr);  // [ 1, 2, 3, 4 ]

push( ) also returns length of the new array.

let arr = [ 1, 2, 3, 4 ];
let arrLength = arr.push( 5, 6, 7 );
console.log(arrLength); // 7

pop :point_right: Using pop() Method Remove an element from end of an Array


Pop method remove the last element in an Array.

let arr = [1, 2, 3, 4];
arr.pop(); // will remove last element
console.log(arr); // [ 1, 2, 3 ]

pop() method also returns the removed element.

let arr = [ 1, 2, 3, 4 ];
let removedLastElement = arr.pop(); 
/*here we have removed last element of array
and  stored it in new variable. */
console.log(removedLastElement);  // 4

shift :point_right: Remove an Element from the front of an Array


Shift remove the first element in an Array.

let arr = [ 0, 1, 2, 3 ];
arr.shift();
console.log(arr);  // [ 1, 2, 3 ]

shift() also returns the removed element from the array.

let arr = [ 10, 20, 30, 40,50 ];
let removedFirstElement = arr.shift();
console.log(removedFirstElement); // 10

unshift :point_right: Add elements to the front of an Array
Using unshift() we can add elements to the front of an array.

let arr = [ 1, 2, 3 ];
arr.unshift(0);
console.log(arr);  // [ 0, 1, 2, 3 ]

unshift() also returns length of the new array.

let arr = [ 4, 5, 6 ];
let arrLength = arr.unshift( 0, 1, 2, 3 );
console.log(arrLength); // 7

If you found this post quite interesting then click on :heart:

Ganesh Patil | TA - Edyoda

3 Likes