Member-only story

Javascript for vs forEach vs for…in loop

Avery Duffin
2 min readJul 2, 2019

--

Photo by Tine Ivanič on Unsplash

Javascript has many features that make it nice to work with. Iterating over objects is one of those features. Classically in programming we use a for loop to iterate over a list of items or objects.

The traditional for loops looks as follows:

for (i = 0; i < 10; i++) { 
// do something
}

This is nice but now you have to worry about indices. This can get a bit hairy and if your like me and hate looking at tons of variables then id use this as a last resort.

Javascript has created two alternatives forEach and for…in

forEach()

If you have an array. Such as the following:

const newArr =  [ 12, 34, 56, 43 ] 

In javascript all arrays have the functional property forEach. You use it by specifying a function that takes a parameter. Everytime your function is called its being called with each item in the array.

const newArr =  [ 12, 34, 56, 43 ]newArr.forEach( (item) => {
console.log(item)
});
// prints
// 12
// 34
// 56
// 43

If you don’t have a need to break early while iterating over an array this is a great function to use.

for…in

--

--

Avery Duffin
Avery Duffin

Written by Avery Duffin

Im a software engineer, react developer, inventor, salesman, family man, religious, and outdoor connoisseur

Responses (4)