2

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]
2
  • so you want a polyfill for pop? returning the last element, and changing your array? Commented Feb 27, 2014 at 21:57
  • "most efficient way" : see the jsperf answer, the one I put is fastest possible polyfill (still 10x slower :P ). I assume this is just for learning Commented Feb 27, 2014 at 23:21

4 Answers 4

4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

The myArray.length = length-1 does not work for empty arrays and throws uncaught RangeError: Invalid array length exceptions, and the splice call in your code needs to access [0] or else it returns a single element or zero element array, instead of the value itself or undefined. :(
1

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.

Comments

0

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

1 Comment

I like the jsperf enthusiasm though :)
-1
Array.prototype.pop=Array.prototype.pop||function(){
    const len = this.length;
    const itemToBePopped=this[len-1];
    this.splice(len-1,1);
    return itemToBePopped;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.