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:
- Another framework, developer, or code might assign a function to the same function name causing a collision
- The function for..in won’t work properly
- Dependability for enterprise software to work as expected
- Might not work properly in every browser
- Maintenance issues when you change the object you don’t own can change dynamically
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.