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.



JavaScript: Tips of the Day

Returns true if the given number is a power of 2, false otherwise

Example:

const tips_isPowerOfTwo = n => !!n && (n & (n - 1)) == 0;
console.log(tips_isPowerOfTwo(0)); 
console.log(tips_isPowerOfTwo(4));
console.log(tips_isPowerOfTwo(16));

Output:

false
true
true