KingKongFrog
KingKongFrog

Reputation: 14419

Javascript - Array pop polyfill code

If I wanted to write the pop function from scratch what would be the most efficient way? The main issue also is how do I return the originating array without the popped element?

Array.prototype.pop = function () {
    var myArray = this;
    var length = myArray.length;
    var element = myArray[length-1];
    myArray = myArray.slice(0,length-1);
    return element;
}

var hello = [1,2,3,4,5];
hello.pop();
5
console.log(hello)
[1, 2, 3, 4, 5]

Upvotes: 2

Views: 1514

Answers (4)

Harish Dhami
Harish Dhami

Reputation: 1086

Array.prototype.pop=Array.prototype.pop||function(){
    const len = this.length;
    const itemToBePopped=this[len-1];
    this.splice(len-1,1);
    return itemToBePopped;
}

Upvotes: -1

Nemo64
Nemo64

Reputation: 2683

Ahh performance... Why do you need that polyfill? Array.prototype.pop is widely supportet!

Anyways I created a little perf test to check that: http://jsperf.com/manual-pop

Upvotes: 0

Andrew Templeton
Andrew Templeton

Reputation: 1696

Short and sweet:

Array.prototype.foo = function(){
  return this.splice(this.length-1)[0];
};

Returns last element or undefined if zero length and modifies the array itself.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Use splice instead of slice - slice doesn't modify the original array, whereas splice does.

That said, since you're removing the last element, it would be return myArray.splice(length-1,1);... which is essentially an alias for return myArray.pop() in the first place.

Alternatively, try:

var element = myArray[length-1];
myArray.length = length-1;
return element;

Upvotes: 4

Related Questions