2

Particularly in its implementation of _.each. It seems like a simple typeof iterator === 'function' would do the trick. Possibly just or it with the obj == null check.

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return obj;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, length = obj.length; i < length; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      var keys = _.keys(obj);
      for (var i = 0, length = keys.length; i < length; i++) {
        if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
      }
    }
    return obj;
  };
  • Probably performance, but you'd best ask somebody on the Underscore development team. – Pointy Jun 27 '14 at 19:34
  • 1
    We can only speculate as to the reasons the author of a script may have had for their implementation. Try asking them rather than the StackOverflow community. – Quentin Jun 27 '14 at 19:34
  • So you'd rather have `_.forEach` **silently fail**, than telling you you passed the wrong value? – Felix Kling Jun 27 '14 at 19:42
  • The function throws an (arguably non-ideal) error when `iterator` isn't a function. – tcooc Jun 27 '14 at 19:57
  • 1
    I don't find this to be opinion based. The method lacks consistency, in one case it returns the obj in the other it lets the language throw an error. I learned in jQuery that there are hardly any errors thrown, that exceptions in JS are not often used. Followining this trend would also allow for more consistency. Consistency and Convention are not opinions. Both are good design choices. –  Jun 27 '14 at 21:07

2 Answers2

1

There is no need for validation. If the input to the function is incorrect, it is caused by a programming error and should be treated as such by blowing up.

Brad
  • 159,648
  • 54
  • 349
  • 530
0

You want to type check it to throw an error if it's not a function? That's what it does if you don't type check it.

Related: Aggressive null-checking in Java.

Community
  • 1
  • 1
djechlin
  • 59,258
  • 35
  • 162
  • 290