forEach, The Better Alternative To a For Loop

This post should be short and sweet. I'll let you on a little secret. I never use for loops.

See this code?

var keys = Object.keys(some_object)  
for(var i = 0; i < keys.length; i++) {  
    console.log(keys[i], ':', some_object[keys[i]])
}

It's meant to loop through all the key-value pairs of an object.

There's a better way:

Object.keys(some_object).forEach((key) => console.log(key, ':', some_object[key]))  

forEach is a method of every JavaScript array. It takes a function as a parameter. It calls that function once for every element it has, passing each individual element to that function.

You may be thinking of other reasons to use for loops. Don't worry, I've got you covered in the next few posts. :)

Looking for a software developer?