Open In App

How to define custom Array methods in JavaScript?

Last Updated : 17 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript arrays are versatile data structures used to store collections of items. When you want to iterate through the elements of an array, it’s common to use loops like for, for…of, or forEach. However, there’s a nuance when it comes to iterating through arrays that have additional properties added through their prototype.

In this article, we will explore how to print only the original properties of an array, excluding any prototype properties, ensuring a clean and accurate output.

Understanding the Prototype Properties:

Before we dive into the solution, let’s understand why arrays might include prototype properties in their iteration.

In JavaScript, you can add properties or methods to the Array prototype. For instance:

Array.prototype.myProperty = function() {
console.log("Hello");
}

If you have an array myArr with elements 10, 15, and 20 and you iterate over it, you’ll notice that it prints the additional myProperty along with the array elements:

Example:

Javascript




Array.prototype.myProperty = function() {
    console.log("Hello");
}
 
const myArr = [10, 15, 20]
 
for (let ele in myArr) {
    console.log(myArr[ele]);
}


Output

10
15
20
[Function (anonymous)]



Filtering Original Properties:

To print only the original properties of an array, excluding prototype properties, you need to perform a check using the hasOwnProperty method. Here’s how you can do it:

Example:

Javascript




Array.prototype.myProperty = function() {
    console.log("Hello");
}
 
const myArr = [10, 15, 20]
 
for (let ele in myArr) {
    if (myArr.hasOwnProperty(ele)) {
        console.log(myArr[ele]);
    }
}


Output

10
15
20



This code ensures that only the original elements in the array are printed, and any prototype properties are ignored.

Conclusion :

When dealing with JavaScript arrays that may have prototype properties, it’s essential to understand how to print only the original properties. By using the hasOwnProperty method, you can iterate through an array while excluding any added prototype properties, ensuring that you obtain the intended results. This knowledge will help you maintain code clarity and avoid unexpected behavior in your JavaScript projects.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads