0

I'm practicing _.every from scratch to learn Javascript, and there are just two lines that I don't understand. Could you articulate what these lines are doing:

if(iterator == undefined) { 
  iterator = _.identity; 

_.every = function(collection, iterator) {
  if(iterator == undefined) { 
    iterator = _.identity; 
  }

  return _.reduce(collection, function(accumulator, item) {
    if (iterator(item)) {
      return accumulator;
    }
    else {
      return false;
    }
  }, true); 
};

I know that _.identity returns the same value that is used as the passed parameter, but I'm not quite seeing how it's applicable here?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rory Perro
  • 441
  • 2
  • 7
  • 16
  • see this question : http://stackoverflow.com/questions/14216479/please-explain-usage-of-identityvalue-of-underscore-js – Luke Aug 04 '15 at 20:42
  • Where did you find that code? That doesn't look anything like the actual source for `_.every()`. – Pointy Aug 04 '15 at 20:48

2 Answers2

1

If the iterator parameter is undefined, that statement makes _.every use _.identity as the default iterator.

Why would that be useful? Because it makes _.every(someArray) be a test to see whether all of the entries in the array are "truthy". For example, if you've got an array that you know contains numbers, and you want to see whether they're all non-zero, you can use _.every() with only one parameter (the array) to make that test.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

_.identity is a function that returns what ever you pass in. f(x) = x

If you call _.every without an iterator, then the iterator is set to _.identity as a default. This allows you to call _.every without passing in your own iterator. It's basically just a convenience, since you could pass in _.identity yourself if you wanted.

chilleren
  • 81
  • 5