Lodash _.reduce returning undefined

The issue

Say you have a method which receives an array, and you use Lodash's _.reduce to check each item one by one. But _.reduce is returning undefined. Here's an example:

console.log(
	_.reduce(
  	[{toBeCounted: 1}, {toBeCounted: 0}],
    function(total, item) 
      {
        if (item.toBeCounted !== 0){
          return total + 1;
        }
      },
    0
  )
);

// Prints 'undefined'

The fix

When you use _.reduce (or the ES6 Array.prototype.reduce), you must always return a value from your reducer function. Here's the corrected code:

console.log(
	_.reduce(
  	[{toBeCounted: 1}, {toBeCounted: 0}],
    function(total, item) 
      {
        if (item.toBeCounted !== 0){
          return total + 1;
        }
        return total;  // This is the fix
      },
    0
  )
);

// Prints `1`
Show Comments

Get the latest posts delivered right to your inbox.