Loading ...
Sorry, an error occurred while loading the content.

3080Re: Array.prototype.reduce

Expand Messages
  • douglascrockford
    Nov 26, 2012
      --- In jslint_com@yahoogroups.com, "rodobrist" <roderickobrist@...> wrote:
      >
      > Hi guys,
      >
      > I was coding and I noticed that I often make the same error from using reduce.
      >
      > e.g.
      >
      > var options = ['nocaps', 'evil', 'node', 'browser'],
      > optionsAsObject = options.reduce(function (options, item) {
      > options[item] = true;
      > }, {});
      >
      > // When it should be:
      > var options = ['nocaps', 'evil', 'node', 'browser'],
      > optionsAsObject = options.reduce(function (options, item) {
      > options[item] = true;
      > return options;
      > }, {});
      >
      > Functions have a default/implied return value of undefined, this means if the array has more than one item this will throw an error.
      >
      > I'm suggesting that if the reduce method is invoked with a non primative second argument and function's first argument has an assignment to its property, there must be an explicit return value.
      >
      > e.g.
      >
      > options.reduce(function (options, item) {
      > // first argument is modified
      > options[item] = true;
      >
      > // Missing return value
      > }, {}); // reduce is invoked with non primative second argument


      I think the error may be that you are using the wrong method: reduce when you should forEach. I am not sure how to test for that.
    • Show all 5 messages in this topic