Array Prototype Functions
Array Prototype Functions
In JavaScript, the Array.prototype is an object that contains properties and methods that are available to all arrays. The properties and methods of Array.prototype are inherited by all arrays, so you can use them on any array in your code.
For example, the push() method is a property of Array.prototype, so you can use it to add elements to the end of an array:
const numbers = [1, 2, 3];
numbers.push(4, 5); // the array is now [1, 2, 3, 4, 5]
You can also use the length property of Array.prototype to get the number of elements in an array:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // prints 5
In addition to the built-in properties and methods of Array.prototype, you can also add your own custom properties and methods by extending the Array.prototype object.
Adding Custom Functions to Array.prototype
For example, you might want to define a sum() method that calculates the sum of all the elements in an array:
Array.prototype.sum = function () {
let total = 0;
this.forEach((element) => {
total += element;
});
return total;
};
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.sum()); // prints 15
Here, we have added a sum() method to the Array.prototype object. This method calculates the sum of all the elements in an array and returns the result. We can now use this method on any array in our code.
Adding Custom Properties to Array.prototype
To add a custom property to the Array.prototype object in JavaScript, you can use the same syntax as you would for adding a method. Simply assign the property to a value or a function, like this:
Array.prototype.customProperty = "This is a custom property";
console.log([1, 2, 3].customProperty); // outputs "This is a custom property"
In this example, we've added a new property called customProperty to the Array.prototype object, and assigned it a string value. We can then access this property on any array instance by using dot notation.
It's generally not recommended to modify built-in objects like Array.prototype, as it can cause unexpected behavior in your code or in third-party libraries. So it's generally best to avoid doing this unless absolutely necessary. If you need to extend the functionality of arrays, it's usually better to create your own utility functions or classes.