Difference between _.forEach and _.forOwn in lodash

ForeachLodash

Foreach Problem Overview


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

Foreach Solutions


Solution 1 - Foreach

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNovellizatorView Question on Stackoverflow
Solution 1 - ForeachThalis K.View Answer on Stackoverflow