Essential Array methods in JavaScript. Part 2 - forEach

#27・

Stay up to date, be part of a community and show your support.

3.66K

subscribers

27

issues

Subscribe to our newsletter

By subscribing, you agree with Revue’s Terms of Service and Privacy Policy and understand that Coderslang: Become a Software Engineer will receive your email address.

Coderslang Master
Coderslang Master
Hey, there! I hope you’re getting closer and closer to your goal of becoming a Full Stack JavaScript developer!
In the previous issue, I’ve introduced to you a method filter that allows you easily filter out the unnecessary elements from your array.
Today, let’s continue with forEach.

How to iterate over array elements with forEach
The next standard task is to iterate over all the elements of the array. It can also be solved with the regular for loop.
Imagine that you need to display the value of all elements of an array, each on a new line.
logging array elements to the console with a regular for loop
logging array elements to the console with a regular for loop
Using a regular for loop, you call the console.log function on each iteration of the loop and pass the current array element arr[i] in it.
The forEach function will allow you to shorten your code a bit. It is similar to the filter function in a way as you’ll also need a handler function to use it. This function will be called for each element of the array.
The fundamental difference is that forEach does not return anything.
forEach that logs array items to the console
forEach that logs array items to the console
Now let’s try to make the example above even shorter as the item => console.log(item) function does nothing with the item parameter other than passing it further down into console.log which outputs the item to the screen.
It turns out that we could use the console.log function without this wrapper from item => ... and the result would remain the same.
console.log is passed directly into forEach as an argument
console.log is passed directly into forEach as an argument
Note that we don’t put parentheses after console.log because we don’t call the console.log function.
We pass it as a parameter to the forEach loop, where it will be applied to each element of the array.
The call will be controlled by forEach, not by us.
This is a very important point at which many interns stumble.
That’s it for now! Next time, I’ll tell you about how you can iterate over an array with the function map, which superpowers it has, and how it’s different from forEach.
Cheers!
Coderslang: Become a Software Engineer
Don’t miss out on the other issues by Coderslang Master
Did you enjoy this issue? Yes No
Coderslang Master
Coderslang Master @coderslang

Coderslang: Become a Software Engineer

You can manage your subscription here.
In order to unsubscribe, click here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Created with Revue by Twitter.