Skip to content

Jamie Pittman

A 30-Something Trying To Get It Right and Helping Others Along the Way

  • About
  • Blog
  • Helpers
  • Portfolio
  • Contact
  • About
  • Blog
  • Helpers
  • Portfolio
  • Contact

forEach in JavaScript: How to Effectively Use It

September 12, 2020October 1, 2020 Jamie Leave a comment
forEach in JavaScript: How to Effectively Use It

*I may be compensated if you purchase through any affiliate links on this site.*

I don’t know about you, but when I started learning how to write JavaScript, forEach() was not on my radar. If I needed to iterate over an array, for loops were #myeverything. When I learned how to use the JavaScript array method forEach(), it changed my code.

When I was going through my coding bootcamp several years ago, we were not being taught JavaScript array methods. I’m not sure if coding bootcamps are now being more thoughtful in including them in the curriculum, but if NOT then this post is for you!

via GIPHY

What does forEach() do?

forEach() iterates over an array in a clean and succinct way. Unlike it’s predecessor (for loop), you don’t have to indicate that the loop should run for the duration of the length of the array. It just does it! Holla!

The forEach() array method executes a function once of each element in an array. It does NOT mutate the original array that you are iterating over. This means that the array will NOT change.

Tell me more about this function being executed…

The function executed on each element in the array is a callback function.

via GIPHY

This function accepts three arguments:

  1. currentValue (required): Represents each value within the array you’re iterating over
  2. index: As in index of the currentValue being looped over
  3. array: As in the array you’re looping over
function(currentValue, index, array)

It also accepts a thisArg as an optional parameter. In fact, I rarely use the index and array parameters. But definitely have used them a few times.

If you want to learn more about these optional parameters, check out the MDN documentation.

Syntax

array.forEach(function(currentValue, index, array))

Now let’s consider a quick example using an array of fruit.

const fruits = [“apple” , “banana” , “orange”]

For now, we are just going to iterate over them and console out the value.

fruits.forEach((element) => { console.log(element)})

//"apple"
//"banana"
//"orange"

Wow! So much easier than a for loop…Am I right?! You can even write this more succinctly using ES6 syntax.

fruits.forEach(element => console.log(element))

Use of the word “element”

You do NOT have to use the word “element” for the currentValue in your callback function. You can name this parameter whatever makes sense for you, but you will commonly see it named “element” or “el”. In our fruits example, you might use the word “fruit” instead of “element”.

When should I use forEach()

When I was first introduced to forEach() it was transformative. Up until that point, I would use a for loop to iterate over an array and then based on specific criteria push elements into a new array. Something like this…

const grades = [33, 90, 78, 94, 56, 88, 97];
const passed = [];

for (var i = 0; i < grades.length; i++) {
  if(grades[i] > 70) {
    passed.push(grades[i])
   }
}

passed = [ 90, 78, 94, 88, 97 ]

I had to Google the syntax because it has been so long!

You can execute the same process using forEach().

const grades = [33, 90, 78, 94, 56, 88, 97];
const passed = [];

grades.forEach((grade) => {
   if(grade > 70) passed.push(grade)
})

passed = [ 90, 78, 94, 88, 97 ]

While it is still possible for you to use forEach() for something like this, it is no longer necessary or best practice with the introduction of the JavaScript array method filter().

forEach() would best to reach for when:

  • You need to iterate over an entire array without breaking the flow
  • No other array methods will solve your problem

via GIPHY

I know, I know. Let me explain…

With the introduction of other array methods like filter(), every(), map(), and more, there is not as much need for using forEach(). I honestly cannot tell you the last time I’ve used it in my code. That’s not to say it’s not important. It is worth knowing and understanding.

That sums it up for forEach()!

Do you use it in your code? What are some examples? Did I miss anything? Comment and let me know!

Photo by Thomas Kinto on Unsplash

codingcoding bootcampforeachjavascriptwomen in tech

Related Posts

4 of The Most Helpful VS Code Extensions & Features for New Web Developers
4 of The Most Helpful VS Code Extensions & Features for New Web Developers
How to Use JavaScript Reduce(): It’s Easier Than You Think
How to Use JavaScript Reduce(): It’s Easier Than You Think
How to Use JavaScript Includes()–It’s Remarkably Easy
How to Use JavaScript Includes()–It’s Remarkably Easy
Is A Coding Bootcamp Worth It? You Need To Ask Coding Bootcamp Students If You Want The Authentic Truth
Is A Coding Bootcamp Worth It? You Need To Ask Coding Bootcamp Students If You Want The Authentic Truth

Post navigation

Is A Coding Bootcamp Worth It? You Need To Ask Coding Bootcamp Students If You Want The Authentic Truth
How to Use JavaScript Includes()–It’s Remarkably Easy

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

4 of The Most Helpful VS Code Extensions & Features for New Web Developers
Blog ➤ January 1, 2021

4 of The Most Helpful VS Code Extensions & Features for New Web Developers

*I may be compensated if you purchase through any affiliate links on this site.* Things have come a long way with code editors since I started my development career four years ago. During my coding...

Read More
How to Use JavaScript Reduce(): It’s Easier Than You Think
Blog ➤ October 24, 2020

How to Use JavaScript Reduce(): It’s Easier Than You Think

*I may be compensated if you purchase through any affiliate links on this site.* I will start this post out by admitting that JavaScript reduce() was the most intimidating array method for me by far....

Read More
One of the Best North Carolina Mountain Vacations: Counting Sheep on a Beautiful Farm
Blog ➤ October 10, 2020

One of the Best North Carolina Mountain Vacations: Counting Sheep on a Beautiful Farm

*I may be compensated if you purchase through any affiliate links on this site.* Last weekend I spent four wonderful days on a North Carolina mountain vacation. My two closest friends and I headed west...

Read More
5 Of The Most Delicious, Limited Time Trader Joe’s Fall Items This Year
Blog ➤ October 3, 2020

5 Of The Most Delicious, Limited Time Trader Joe’s Fall Items This Year

*I may be compensated if you purchase through any affiliate links on this site.* It’s fall y’all! And for me, one of my favorite parts is about this season is Trader Joe’s fall items. It’s...

Read More
How to Use JavaScript Includes()–It’s Remarkably Easy
Blog ➤ September 30, 2020

How to Use JavaScript Includes()–It’s Remarkably Easy

*I may be compensated if you purchase through any affiliate links on this site.* The JavaScript array method includes(), like so many other array methods, does what its name proclaims: it will check an array...

Read More

Subscribe

Stay up to date with our latest posts and news!

Categories

  • A Better Me (1)
  • Blog (19)
  • Career (9)
  • Coding (14)
  • Finance (1)
  • Food (1)
  • Lifestyle (1)
  • Pages (4)
  • Travel (1)
  • Travel (1)
  • Tutorials (2)
  • Wellness (1)

Instagram

Hey, There!

Hey, There!

Jamie Pittman, Founder

Welcome to my blog! Here you'll find stories from my life, advice about your career, and blogs about all the things I love. Contact me!

Recent Posts

  • 4 of The Most Helpful VS Code Extensions & Features for New Web Developers
  • How to Use JavaScript Reduce(): It’s Easier Than You Think
  • One of the Best North Carolina Mountain Vacations: Counting Sheep on a Beautiful Farm
  • 5 Of The Most Delicious, Limited Time Trader Joe’s Fall Items This Year
  • How to Use JavaScript Includes()–It’s Remarkably Easy
  • About
  • Blog
  • Helpers
  • Portfolio
  • Contact
© 2021 | Designed by Little Theme Shop