Enhancing JavaScript Arrays: Good or Bad?

This is a way to give JavaScript Arrays some extra functionality to make life easier for development and in turn lead to clear and concise code.

I’ve mentioned some ways to give backwards compatibility functionality (otherwise known as Polyfilling) to the Array object in browsers such as IE8. This is generally considered good and proper. Even the Mozzila MDN advocates for it.

Here are a couple of ways to extend the native JavaScript Object Array with other functions to simplify interactions with an array of objects.

JavaScript

// Checks if the array contains the element e under the property in an array of objects
Array.prototype.has = function(e, property) {
  for (var i=0; i < this.length; i++){
    if (this[i][property] == e) return true;
  }
  return false;
}

// Retrieves the maximum value nested inside an object in an array of objects
Array.prototype.max = function (property) {
  var arr = this.map(function (e) {
    return e[property];
  });
  return Math.max.apply(Math, arr);
};

// Retrieves the minimum value nested inside an object in an array of objects
Array.prototype.min = function (property) {
  var arr = this.map(function (e) {
    return e[property];
  });
  return Math.min.apply(Math, arr);
};

However, Google advocates to not do this in their JavaScript Style Guide. The reasons, I can think of, why they would go for this approach are:

Some of the drawbacks can be addressed by having internal development standards and practices. Indeed the three methods above allow you to have very maintainable and reusable code if documented and used internally. But if you are creating a framework or web part that can be consumed by something or someone else, it’s best to heed the advice of Google if you are extending with new functions rather than polyfilling.

 
7
Kudos
 
7
Kudos

Now read this

Spirally Traversing a Two-Dimensional Array in JavaScript

This is a way to traverse a two-dimensional array (or a matrix) from the top left, spirally in a clockwise manner in JavaScript. This solution is inspired by functional programming and it uses tail recursion. Steps: When you start with... Continue →