JavaScript array.prototype Property

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript array.prototype Property
  2. Example 1: Use array.prototype to Get the Custom Word Added in Elements of the Array
  3. Example 2: Use array.prototype With the Function to Create a Prototype for the Array
JavaScript array.prototype Property

In JavaScript, the array.prototype property can be used for every array. This method allows us to set functions or words for the elements in an array and change its length.

Syntax of JavaScript array.prototype Property

Array.prototype.func = function() {
    console.log(this[0]);
};
let arr = ["Delft","stack"];
arr.func();

Parameters

arr It is a reference array on which we need to call any function defined in array.prototype.
this[i] It represents the value of the ith element of the arr.

Return

This method changes the actual output of the array and returns the array based on the method used to create the prototype.

Example 1: Use array.prototype to Get the Custom Word Added in Elements of the Array

The array.prototype property allows us to add functions to create a prototype for the given array. In this example, we have created an array and added a function that will be used to create a prototype for an array with the array.prototype property.

const array = ["JavaScript", " C++"];
Array.prototype.val= function () {
for (let i = 0; i < this.length; i++) {
this[i] = this[i].toUpperCase() + " Language";}};
array.val();
console.log(array);

Output:

[ 'JAVASCRIPT Language', ' C++ Language' ]

Example 2: Use array.prototype With the Function to Create a Prototype for the Array

The array.prototype property creates the prototype for the given array. In this example, we have created an array.

In the function, we used the increment method so that the prototype could be created for every element in the array. Then, we used the array.prototype property to access the function and change the actual output of the array.

Array.prototype.setvalue = function() {
for (let i = 0; i < this.length; i++) {
this[i] = this[i] + " file";}}
let array = ['1','2'];
array.setvalue()
console.log(array);

Output:

[ '1 file', '2 file' ]

The array.prototype method is supported in all browsers of the current version.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript Array