54

What is the difference between these two methods when iterating over an object?

Novellizator
  • 13,633
  • 9
  • 43
  • 65

2 Answers2

76

The difference lies in that if the collection over which you are iterating is an object which has a length property, then the _.forEach() will iterate over it as if it were an array, whereas the _.forOwn() will iterate over it like an object.

Assume you have the object:

a = {
  x: 100, 
  y: 200, 
  length: 2
}

If you iterate over it as:

_.forEach(a, function(val, key) {
  console.log('a[' + key + '] = ' + val); 
});

you'll get output:

a[0] = undefined
a[1] = undefined 

whereas iterating over it with _.forOwn() you'll get the more reasonable:

a[x] = 100
a[y] = 200
a[length] = 2
Yves M.
  • 29,855
  • 23
  • 108
  • 144
Thalis K.
  • 7,363
  • 6
  • 39
  • 54
  • This is a poor example because I have used _.forEach and _.each to iterate over objects hundreds of times in code I have written. Even the lodash official docs show examples of each and forEach iterating over object. The reason you are getting undefined is because your object has a key value pair where the the key is "length" and if you create a normal object without "length" it will iterate – PrimeLens Mar 23 '23 at 13:15
0

As per the docs for forOwn the iterator must be an object. With _.each and .forEach you can use this on array or an object.

PrimeLens
  • 2,547
  • 4
  • 23
  • 28