The Simple For Loop

First a quick introduction to the for loop. One of the first looping mechanisms we learn as developers along with the do while.

A simple for loop with fibonacci sequence
Another Example with for loop

Now let’s put another example with an array of objects

A for loop iterating through an array of objects
Some Drawbacks of For Loop

The for loop has 3 statements we must define. Most IDE/text editors offer a shortcut for this, but still it introduces three opportunities for human error before we do any logic within the loop


Like at in this previous example someone could accidentally decrement i, set the terminal condition for the for loop <= , in which cases it loops over a phantom element.

Equivalent with .forEach()

Let’s do the same with .forEach with the for loop commented out so we can see the syntactic difference. The .forEach is on the array through Javascript’s prototypical inheritance.

Let’s also go through the example with the array of objects.

and we get the same results

output of .forEach loop iterating through an array of objects
Limitations of .forEach()


As I alluded to earlier the for loops has 3 statements you have to define, and therefore 3 opportunities to make mistakes. Not that the forEach loop isn’t without limitations which I will get into later.

You can break out of a for-loop quicker. For example if you want to stop the loop once something has a occurred, whether that be something is found in an array. Then you can use break in a for loop, but in forEach there is no such luxury.

 

No Easy Decrementing


No Easy Decrementing

You if you’d like to start from the end of an array towards the beginning their isn’t really a non-clunky solution.

No Binary Search


No Easy Decrementing

You if you’d like to start from the end of an array towards the beginning their isn’t really a non-clunky solution.

No Binary Search

You won’t be able to setup pointer’s in a sorted array to conduct a binary Search

Continue Your Learning

Here at CodingPhase we offer a comprehensive Future-Proof Javascript and ESNEXT – ES6, ES7, ES8 which will cover all the modern Javascript. Hiring managers are looking for people who are up to date with the latest language specifications

Sign up for a monthly subscription for $20/m and also get access to our  Object Oriented Programming with Javascript  and our Learn React by Building a Craigslist Clone