DEV Community

Cover image for JavaScript Array Series – Creating Own push() Method
Vairavan
Vairavan

Posted on

JavaScript Array Series – Creating Own push() Method

In my previous blogs, I explained how the JavaScript length property works and also created my own version of the toString() method without using JavaScript's built-in methods.

Today, I continued this learning journey by creating my own version of another important array method: push().

Instead of using JavaScript's built-in push() method, I tried to understand how it works internally by implementing it manually.

What is push() Method?

The push() method is used to add a new element at the end of an array.

Example:

const arr = [1, 2, 3];

arr.push(4);

console.log(arr); // [1, 2, 3, 4]

Enter fullscreen mode Exit fullscreen mode

In this blog, I did not use the built-in push() method. Instead, I created my own logic.

My Approach

const arr = [1, , 3, 4, 5];
let user = "gunalan";

arr[countOfLength()] = user;

function countOfLength() {
    let lengthDemo = 0;

    for (let count of arr) {
        lengthDemo++;
    }

    return lengthDemo;
}

console.log(arr);
Enter fullscreen mode Exit fullscreen mode

How Does This Work?

Step 1: Create an Array and a New Value

const arr = [1, , 3, 4, 5];
let user = "gunalan";
Enter fullscreen mode Exit fullscreen mode

Here, I created an array and a new value that needs to be added.

Step 2: Find the Length of the Array

function countOfLength() {
    let lengthDemo = 0;

    for (let count of arr) {
        lengthDemo++;
    }

    return lengthDemo;
}
Enter fullscreen mode Exit fullscreen mode

I created a custom function called countOfLength().

Inside this function:

I started a variable named lengthDemo with value 0. Then I used a for...of loop to visit every element in the array.
For each iteration, I increased lengthDemo by 1.
Finally, I returned the total count.

Step 3: Add the New Value

arr[countOfLength()] = user;
Enter fullscreen mode Exit fullscreen mode

After finding the length, I used that value as the new index.

For example, if the array length is 5, the new value will be added at index 5.

This is similar to how the original push() method works.

Output:

[1, empty, 3, 4, 5, "gunalan"]

Enter fullscreen mode Exit fullscreen mode

What I Learned

By creating this custom push() method, I learned:

✅ How the push() method adds values to an array.

✅ How array indexes work internally.

✅ How to create custom functions.

✅ How loops can be used to recreate built-in methods.

Conclusion

  • Implementing JavaScript methods manually is one of the best ways to understand how JavaScript works behind the scenes.
  • Every day, I am trying to recreate built-in methods step by step. This process is helping me improve my JavaScript fundamentals and problem-solving skills.
  • I will continue this series by implementing more JavaScript methods

Stay tuned for the next blog! 👋

Top comments (0)