Can you implement forEach() correctly?
Tags: javascript, node, opensource
Published: 2020-05-15 10:57:20

---
title: Can you implement forEach() correctly?
published: true
description: It sounds simple but there is a catch, a minute but distinctive one
tags: javascript, node, opensource
---

So if you're into JavaScript you may be using **forEach()** daily. Let's dive deep into and see whether we can implement our own forEach() or not. 

## forEach() usage

> The forEach() method executes a provided function once for each array element. - MDN

```javascript
const arr = [1, 'ashok', 3, 4]
arr.forEach(el => console.log(el));
```

So how you'll move forward with implementing your own **forEach()**?
We have to iterate through the elements with the given callback, Simple!

```javascript
function myEach(callback) {
  for (let i = 0; i < this.length; i += 1) {
    callback(this[i], i, this);
  }
}
```
Done? No, you will say we can make it even more realistic by adding it to the Array prototype chain and rule like a King.

Ok, here you go!

```javascript
Array.prototype.myEach = function myEach(callback) {
  for (let i = 0; i < this.length; i += 1) {
    callback(this[i], i, this);
  }
};
```
I hope now it's complete. Yay!

## Voila! 

**The above implementation floating around the web is wrong.** Find the [ECMA Specification here](https://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.foreach)

## Know your forEach() better

forEach() calls a provided callback function once for each element in an array in ascending order.

**It is not invoked for index properties that have been deleted or are uninitialized**<sup>1</sup>

The above point is something people are not caring about when implementing forEach, to keep things simple, I am skipping the implementation of the 3rd argument **this** as you can see in the signature `arr.forEach(callback(currentValue [, index [, array]])[, thisArg])`

```javascript
Array.prototype.myEach = function myEach(callback) {
  for (let i = 0; i < this.length; i += 1) {
    callback(this[i], i, this);
  }
};

const arr = [1, 'ashok', 3, 4]
// let's delete one of the elements
delete arr[1];

// native
arr.forEach(el => console.log(el));
console.log('-------')
// testing myEach()
arr.myEach(el => console.log(el));

```

Can you guess the output of the above two? Here is the output:

![Code Output](https://dev-to-uploads.s3.amazonaws.com/i/cfem8ggx32qaql50ukfb.png)

Did you notice that our implementation of the **myEach()** enumerates on deleted indexes as well? 

This has something to do with **Prototype Chain** I am not willing to cover it here but we can fix this using `.hasOwnProperty()`

```javascript
Array.prototype.myEach = function myEach(callback) {
  for (let i = 0; i < this.length; i += 1) {
    if (Object.hasOwnProperty.call(this, i)) {
      callback(this[i], i, this);
    }
  }
};
```

We can step further and can reduce some code if we can directly run `hasOwnProperty()` on the current instance i.e **this**

```javascript
Array.prototype.myEach = function myEach(callback) {
  for (let i = 0; i < this.length; i += 1) {
    if (this.hasOwnProperty(i)) {
      callback(this[i], i, this);
    }
  }
};

```
Now you can test this and celebrate that we covered the most distinctive feature of **forEach()**

**Few people are implementing the built-in JS methods** Have a look here:

{% github knaxus/native-javascript %}


I hope you liked it! For digging deeper, here is one more article: [https://alligator.io/js/foreach-array-method/](https://alligator.io/js/foreach-array-method/)