More

    How To Create A (forEach) Custom Array Helper Method In JavaScript

    In this tutorial, I will be showing you how to create your own custom array helper function in JavaScript.

    Please note that this tutorial is no way trying to replace the inbuilt forEach array helper method, and in fact, you should use the default array helpers when and where necessary. This is just to show you what in a little more simple term what goes on behind the scene.

    You need to be familiar with any of the loop methods to to this, but don’t worry, even if you are new to programming, JavaScript or loops, I’ve got you covered. We will be using the for loop in this tutorial.

    What is the first step to creating our custom forEach method/function?

    Because we are trying to replicate the forEach method, we need to know the structure of the forEach method, more on it can be found here.

    The inbuilt forEach method takes in a callback function and the callback function takes about four (4) arguments:

    • currentValue -> This is the current element that is being processed inside the array. This is a required value that must be passed in the arguments. it is also the first argument in the forEach() (forEach function).
    • index (Optional) -> This is the current position or index of currentValue the processed in the array and it begins from 0 upwards. it is a typeof “number”.
    • array (Optional) -> This is the array the forEach() was called upon.
    • thisArg (Optional) -> According to the MDN docs, it is value to use as this when executing callback. (I never used this before).

    Please note that a forEach returns undefined at the end of execution.

    Now, before implementing out custom forEach function, lets see the usage of the forEach function.

    const arr = ['Rice', 'Beans', 'Beef', 'Fish', 'Water'];
    
    arr.forEach((e) => console.log(e));
    
    forEach Result

    That above is the default forEach method we get for free in JavaScript. now what if we want to create ours ourself? Below is how we go about it:

    const arr = ['Rice', 'Beans', 'Beef', 'Fish', 'Water'];
    
    Array.prototype.myForEach = function(callback) {
        for (let i = 0; i < this.length; i++) {
            callback(this[i], i, this)
        }
    }
    
    arr.myForEach(e=> console.log(e))
    
    Custom forEach Result
    myForEach Result (custom array helper)

    If you look at the above code closely, it is working fine already but there is something missing. we are not checking the case of when it is been used on non arrays when its been called on null or undefined which might end in giving us undesired result or errors, in that case what do we do?

    We need to prepare our helper method to check and guard against those scenarios and how do we do that? Below is the solution to the problem:

    const arr = ['Rice', 'Beans', 'Beef', 'Fish', 'Water'];
    
    Array.prototype.myForEach = function(callback) {
        if (!this) {
            return console.error("You cannot use 'myForEach' on a null or undefined")
        }
    
        if (typeof callback !== 'function' || !callback) {
            return console.error("The provided callback is not a function, please check and try again")
        }
    
        for (let i = 0; i < this.length; i++) {
            callback(this[i], i, this)
        }
    }
    
    arr.myForEach(e=> console.log(e))
    

    And thats it. we have created our own custom forEach function named myForEach and it can do everything that the forEach can do.

    Note, that you can name it however you please and also, this is not restricted to only for loop, you can also use while loop and do while loop as well.

    Once again, I will like to say that you should not reinvent the wheel by creating something that has already been created for you. You should not use this in a production as you can always use the forEach function provided for you.

    This tutorial was just to show what is going on behind the scene and help you get more in-depth on how your code is working.

    This will be a series as we will treat all array helper function and recreate them.

    If you enjoyed this post or found it useful, please share and subscribe for more free educative contents.

    Recent Articles

    How To Create A (forEach) Custom Array Helper Method In JavaScript

    In this tutorial, I will be showing you how to create your own custom array helper function in JavaScript. Please note that this tutorial is...

    Related Stories

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Stay on op - Ge the daily news in your inbox