Difference between push() and unshift() methods in javascript

JavascriptObject Oriented ProgrammingFront End Technology

The unshift method adds the element at the zeroeth index and shifts the values at consecutive indexes up, then returns the length of the array.

The push() method adds the element at end to 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.push("pinapple"))
console.log(fruits2.unshift("pinapple"))
console.log(fruits)
console.log(fruits2)

Output

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

Note that both the original arrays were changed here.

Unshift is slower than push because it also needs to unshift all the elements to the left once the first element is added.

raja
Published on 16-Sep-2019 07:06:55
Advertisements