1

In recent interview, interviewer has asked can you write polyfill for push() method in javascript.

any one know how to do this .?

2 Answers 2

2

push() adds one or more elements at the end of array and returns new length of array. You can use array's length property to add element at the end of it.

if (!Array.prototype.push) {
// Check if not already supported, then only add. No need to check this when you want to Override the method

    // Add method to prototype of array, so that can be directly called on array
    Array.prototype.push = function() {

        // Use loop for multiple/any no. of elements
        for (var i = 0; i < arguments.length; i++) {
            this[this.length] = arguments[i];
        }


        // Return new length of the array
        return this.length;
    };
}
Sign up to request clarification or add additional context in comments.

3 Comments

You also need to update this.length to make Array.prototype.push generic. So somewhere add this.length = Number(this.length) || 0; and this.length += 1.
@KingMob I don't think that is needed. As if you have empty array, it's length will be always zero, no need to set this. And this.length += 1 is not needed, as you're adding new elements in array, length will be automatically incremented by one, for each addition
I mean for Array.prototype.push.call on, e.g. {length: 0}.
1

if (!Array.prototype.push) {
  Array.prototype.push = function () {
    for (var i = 0, len = arguments.length; i < len; i++) {
      this[this.length] = arguments[i];
      if (Object.prototype.toString.call(this).slice(8, -1).toLowerCase() === 'object') {
        this.length += 1;
      }
    }
    return this.length;
  };
}

1 Comment

Maybe you could add some explanation so the OP can understand better?

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.