How to Extend a List in JavaScript?

Estimated read time 1 min read

In JavaScript, you can extend a list (or array) by adding new methods to the Array prototype. Here’s an example of how to extend the Array prototype:

Array.prototype.sum = function() {
  var total = 0;
  for (var i = 0; i < this.length; i++) {
    total += this[i];
  }
  return total;
};

In this example, we’re adding a new method called sum() to the Array prototype. This method calculates the sum of all the elements in the array it’s called on.

Here’s how you can use the sum() method:

var nums = [1, 2, 3, 4, 5];
console.log(nums.sum()); // 15

To extend the Array prototype, you can define a new function on the prototype object. The function can then be called on any array value, just like any other method on the Array object.

Note that extending built-in prototypes is generally considered a bad practice, as it can cause conflicts with other code and make it harder to maintain and debug your code. It’s often better to create your own utility functions and methods instead of modifying built-in prototypes. If you do decide to extend a built-in prototype, be sure to document your changes clearly and thoroughly test your code to avoid unexpected behavior.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply