w3resource

JavaScript prototype Property: Array Object

Description

The prototype property is used to add new properties or methods to an array object.

Version

Implemented in JavaScript 1.1

Syntax

myobj.prototype.name = value

myobj: The name of the constructor function object you want to change.

name: The name of the property or method to be created.

value: The value initially assigned to the new property or method.

If you add a property to the prototype for an object, then all objects created with that object's constructor function will have that new property, even if the objects existed before you created the new property.

Example:

In the following web document, we add a method to the array object which returns the lowest value element of the array.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8" />
<title>JavaScript Array object - constructor property example</title>
<style type="text/css">
h1 {color:red}
</style>
</head>
<body>
<h1>JavaScript Array Object : prototype Property</h1>
<script src="array-prototype-example1.js"></script>
</body>
</html>

JS Code

function array_min_value()
{
 var ctr, min_value = this[0];

   for (ctr = 1; ctr < this.length; ctr++)
   {
   if (min_value > this[ctr])
{
   min_value = this[ctr];
}
   }
   return min_value;
}
Array.prototype.min = array_min_value;
var a = new Array(111, 123, 126.99, 100, 500);
var b = a.min();
var newParagraph = document.createElement("p");
var newText = document.createTextNode("The lowest element in the array is : "+b); 
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph);

View the example in the browser

Practice the example online

See the Pen array-prototype-1 by w3resource (@w3resource) on CodePen.


See also:

JavaScript Core objects, methods, properties.

Previous: JavaScript length Property: Array Object
Next: JavaScript concat() Method : Array Object

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript/object-property-method/array-prototype.php