Maximum number of values in an array I have an array to have a maximum of 10 elements. Whenever I add a new element, if it already has 10, it would remove the first and push a new one.

I made this:

Array.prototype.pushMax = function(value,max){

     if (this.length &gt;= max){
           this.shift();
     }
     this.push(value);

}


Which seems to work fine, however, I'm just wondering if there is a better way to do it (perhaps some native JavaScript function)
There is no native way to do this so your general logic seems sound.  Here's some improvements, you might consider:


Make sure the pushMax function is not enumerable so people who iterate arrays with for (var index in array) won't see the pushMax property.
Ensure the array stays below max length even if it was previously above max
Return the new length of the array, the same as .push():


Here's a working snippet:



Object.defineProperty(Array.prototype, "pushMax", {
    configurable: false,
    enumerable: false,
    writable: false,
    value: function(value, max) {
        if (this.length &gt;= max) {
           this.splice(0, this.length - max + 1);
      }
      return this.push(value);
    }
});



var x = [0,1,2,3,4,5,6,7,8,9,10];
x.pushMax(11, 10);
x.pushMax(12, 10);
x.pushMax(13, 10);

// wrong way to iterate an array, but just testing enumerability
for (var i in x) {
    document.write(i + ": " +  x[i] + "&lt;br&gt;");
}






You could also consider making the max length be a non-enumerable property of the array so you don't have to pass it to .pushMax() every time.



I'd really rather see this in a subclass of an Array rather than modifying the built-in Array object, but alas we can't subclass the Array object yet in most browsers.