DEV Community

Cover image for Picky Picky with forEach()
Wayne Gakuo
Wayne Gakuo

Posted on

Picky Picky with forEach()

This article is meant to introduce you to some of the powerful capabilities of the "mighty for loop" alternatives in JavaScript(JS from now).

If you're new to the JS programming language, click here to have a quick read on its history: http://bit.ly/36cSCHO

For the purpose of simplicity, I will be using the ES6 syntax to show how JavaScript code works. More to read about ES6 here: http://bit.ly/JS_ES6

The famous for loop function has been in existence since the introduction of programming languages, but in this case, we will focus on JavaScript. The forLoop function is used to traverse through an array of items or objects and then do "something" after that

Below is how the forLoop function works.

const arr = [1, 5, 6, 3, 2]

for(i=0; i< arr.length; i++){
    console.log(arr[i])
} // results: 1, 5, 6, 3, 2
Enter fullscreen mode Exit fullscreen mode

We are simply going through the whole array using 'i' and making sure that we are within the given array's length and printing the items one-by-one.

Now this may look cumbersome to some people who would need something simple & straightforward. Here comes in the "forEach()" function. Below is how the same code above would be implemented.

const arr = [1, 5, 6, 3, 2];

arr.forEach(i => {
            console.log(i)
        })
//result: 1, 5, 6, 3, 2
Enter fullscreen mode Exit fullscreen mode

And voila! You just made use of the forEach() function without having to state the limit or have to use the "i++" to show iteration.

Be sure to check in soon for another article of the "forLoop alternatives" series.

Top comments (4)

Collapse
 
mayeedwin profile image
Maye Edwin

Ayee, we also have for...of, for..in; just understand when to use each them.

Collapse
 
wayne_gakuo profile image
Wayne Gakuo

Sure! All about preference.

Collapse
 
zenocodes profile image
Azron Brian

Preference really? I look forward to your article on both with respect to arrays & objects.

Collapse
 
zenocodes profile image
Azron Brian

Absolutely.