QUESTION: What is the problem with both snippets below?
[].reduce((previous, current) => {
return previous + current;
});
''.split('').reduce((previous, current) => {
return `${previous}-${current}`;
});
[].reduce((previous, current) => {
return previous + current;
});
''.split('').reduce((previous, current) => {
return `${previous}-${current}`;
});
ANSWER: Correct:
The problem is that with empty arrays and no default initial values for reduce
, the JS engine doesn't have anything to return and throws an exception.
TIP: Always provide an initial, default value for your reduces. 0 or 1 for reduces that sum or subtract, 1 for addition and subtraction, empty string for strings. For other cases, consider each one carefully.
[].reduce((previous, current) => {
return previous + current;
}, 0);
''.split('').reduce((previous, current) => {
return `${previous}-${current}`;
}, '');