How to make a “foreach” function in JavaScript

I thought this would be a simple exercise in case of having to interview someone for a JavaScript position.

“How would you make your own ‘foreach’ in JavaScript”

I came up with the following solution:

// collection: A list of objects.
// onElementIterationCallback: The function to be called on every element iterated
//    taking the following parameters:    foo(collection : [T], currentIndex : int)
function foreach(collection, onElementIterationCallback) {
    for (var i in collection) {
        if (collection.hasOwnProperty(i)) {
            onElementIterationCallback(collection[i], i);

This is how you’d use it:

var sumOfAges = 0;
var people = [ {name:"Angel", age:35},
               {name:"Paulina", age:33},
               {name:"Nicole", age:16}]

foreach(people, function (person, currentOffset) {
   console.log("("+ currentOffset + ") iterating on " + 
      + ", age: " + person.age);
   sumOfAges += person.age; 


The expected output would be:

(0) iterating on Angel, age: 35
(1) iterating on Paulina, age: 33
(2) iterating on Nicole, age: 16

Hope you enjoyed, just a simple exercise of lists, creativity and callbacks.

Submit a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.