I tried to make a function working same as Array.prototype.reduce method.
function a(collection, iterator, accumulator) {
for (i of Object.keys(collection)){
if (i===0 && accumulator === undefined){
accumulator = collection[i]
continue
}
accumulator = iterator(accumulator, collection[i])
}
return accumulator;
};
a([1,2,3],function(acc,cur){return acc += cur}, 0) // this works fine. returns 6
a([1,2,3],function(acc,cur){return acc += cur}) // expected 6 but returns NaN
a([1,2,3], function(memo){return memo}); // expected 1 but returns undefined
I don't know why accumulator does not set as collection[i] and keep stayed as undefined when the initial value (the third parameter of function a) not delivered.