js
In this article, we will learn about four array methods i.e. push(), pop(), shift() and unshift() which allow us to add and remove elements from beginning and end of an array.
Using push() we can add elements to the end of an array.
let arr = [ 1, 2, 3 ];
arr.push(4);
console.log(arr);
// [ 1, 2, 3, 4 ]
push() returns length of the new array.
let arr = [ 1, 2, 3, 4 ];
let arrLength = arr.push( 5, 6, 7 );
console.log(arrLength);
// 7
Pop remove the last element in an Array.
let arr = [1, 2, 3, 4];
arr.pop();
console.log(arr);
// [ 1, 2, 3 ]
pop() returns the removed element.
let arr = [ 1, 2, 3, 4 ];
let removedElement = arr.pop();
console.log(removedElement);
// 4
Shift remove the first element in an Array.
let arr = [ 0, 1, 2, 3 ];
arr.shift();
console.log(arr);
// [ 1, 2, 3 ]
shift() returns the removed element from the array.
let arr = [ 0, 1, 2, 3 ];
let removedElement = arr.shift();
console.log(removedElement);
// 0
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() returns length of the new array.
let arr = [ 4, 5, 6 ];
let arrLength = arr.unshift( 0, 1, 2, 3 );
console.log(arrLength);
// 7