DEV Community

Cover image for Unleashing the Power of Customized Array Methods in JavaScript.

Unleashing the Power of Customized Array Methods in JavaScript.

Vishal Nayak on February 18, 2024

In the realm of JavaScript, arrays serve as the backbone of many operations. They offer a flexible structure to store and manipulate data efficient...
Collapse
 
annetawamono profile image
Anneta Wamono

Thank you for the article! I didn't even know you could make custom array functions.

I get a little lost with the callback parameter in the customFilter. What does this line mean:

callback(this[i], i, this)

Collapse
 
nvish007 profile image
Vishal Nayak • Edited

Thank you for your response!!
In the line callback(this[i], i, this), the code is invoking the callback function that is passed as an argument to the customFilter method.

  • this[i]: This refers to the current element of the array that is being iterated over in the filtering process.

So, callback(this[i], i, this) is passing three arguments to the callback function:

  1. this[i]: The value of the current element in the array.
  2. i: The index of the current element.
  3. this: The entire array itself.

In the context of the example usage,

var evenNumbers = numbers.customFilter(function(num) {
    return num % 2 === 0;
});

Enter fullscreen mode Exit fullscreen mode

The callback function checks if a number is even by evaluating num % 2 === 0. It only returns true for even numbers, which means it filters out odd numbers when used with the customFilter method.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

It's generally considered bad practice to do this, as there is no guarantee that the methods you create will not conflict with other libraries, or with future extensions to the JS language itself.

The only safe way that I know of to add methods to native prototypes is to name those methods with Symbols as the names of the methods - which guarantees that they will not conflict with anything. In fact, I built a whole library based around this idea:

Another way to go would be to make your own array class that subclasses and extends the original array class.