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)]



How to define custom Array methods in JavaScript?

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.

Similar Reads

Understanding the Prototype Properties:

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

Filtering Original Properties:

...

Conclusion :

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:...