DEV Community

jyeett
jyeett

Posted on

Breaking Down Array Iterator Methods with Callback Functions

At first glance, figuring out how to use all the different array methods can be confusing and difficult to understand. Why is there a function declaration inside my array? What does the arrow I see so often do? Where did that random variable inside the method come from?? Isn't that variable undefined???

It doesn't have to be this complicated even if it looks like it. Once you understand the pattern these array methods share, you will be able to take any array and mutate its data to your heart's content.

The Array Methods

Now there are many array methods, but our focus will be those that take in callback functions. A few common ones to name are map, filter, forEach, find, and reduce. What makes these methods so special as to take in a completely new function? They are iterable methods! That means it will look through each individual element in the array and perform the function that is declared. The array methods do have their specific purposes though, so be mindful of what you want to accomplish and choose the appropriate method. It is best to know what you want to do with your data during and after the method call and then check the return value of your method.

The Callback Function

If you look at an MDN document for your array method, for example map, you will see under the parameters "callbackFn". This means you must create a function inside of your method call. There is more than one way to do this so we will take a look to better understand how they work.

Here we are creating an anonymous function with a parameter of element. Our map method will iterate through our array and one at a time, pass each element to the function we created. Every time our callback function returns, it will add the modified element to a new array. Once map passes through all the elements in the array, we will have a new array with each element acted upon by our callback function.
Anonymous function

A similar, shorter alternative will be to use an arrow function. Here we can use the element parameter in the same manner and take advantage of the arrow function's implicit return.
Image description

To show the same callback function structure in another array method, let's take a look at filter. Again, our element parameter is looking at each individual element and our function is implicitly returning a boolean based on the condition that the element is not yellow. Filter will add to a new array each element that returns true in that condition.
Image description

Conclusion

At a basic level it is the most important to understand how our callback function works within array methods. Identify what the parameter is and what kind of elements are going to be passed in. Once the concept of iterating through the array one element at a time clicks, you will be ready to tackle any of the array iterator methods.

Discussion (0)