Member-only story
Javascript for vs forEach vs for…in loop
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.