0
function each(collection, callback) {
  if (Array.isArray(collection)) {
    for (var i = 0; i < collection.length; i++) {
      callback(collection[i]);
    }
  }
  else {
    for (var prop in collection) {
      callback(collection[prop], prop, collection);
    }
  }
}


var array = [1, 2, 3, 4, 5];


function reduce(collection, callback, initial) {
  var current = initial;
  each(collection, function(current, e) {
    current = callback(current, e);
  })
  return current;
}

console.log(reduce(array, function(a, b) { return a + b }, 0));  -->>> 0

I'm trying to rewrite the underscore each/reduce functions, and use the each function in reduce. I know that I have a mistake in there-- (current should not be in the each callback function) it should be just be

each(collection, function(e) {
  current = callback(current, e);
})

and that returns 15 as it should, but why does it return 0 when you do add that current in there as a parameter? Shouldn't it just return NaN? As the last part of the loop will try to add 5 and undefined which is NaN.

3
  • Just a comment, you really should check .hasOwnProperty() in your each() function for the case when the collection is not an array Commented May 15, 2015 at 4:38
  • 1
    Because when you add current as a parameter, you override the outer scope variable, and end up never changing it's initial value Commented May 15, 2015 at 4:43
  • Not related to your problem, but if you are going to pass prop and collection to the callback in the case of an object, shouldn't you also pass i and collection in the case of an array? Commented May 15, 2015 at 4:51

1 Answer 1

3

The thing is that as soon as you add current to the parameter list of your callback function, you do have two variables - with the same name, but in different scopes. The one in the callback does shadow the one in the reduce function.

So your callback reducer is called with the element that each passed to your callback and undefined, but when assigning the result (NaN) to current it will just assign to the local variable of your each callback.

The outer current variable will stay completely unaffected, and when it is returned from reduce it still holds the initial value it was initialised with - 0.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.