Difference between shift() and pop() methods in Javascript

JavascriptObject Oriented ProgrammingProgramming

The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned.

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

Example

let fruits = ['apple', 'mango', 'orange', 'kiwi'];
let fruits2 = ['apple', 'mango', 'orange', 'kiwi'];
console.log(fruits.pop())
console.log(fruits2.shift())
console.log(fruits)
console.log(fruits2)

Output

kiwi
apple
[ 'apple', 'mango', 'orange' ] 
[ 'mango', 'orange', 'kiwi' ] 

Note that both the original arrays were changed here.

Shift is slower than pop because it also needs to shift all the elements to the left once the first element is removed.

raja
Published on 16-Sep-2019 07:03:11
Advertisements