I’m using a Reduce function for a spesific reason in my Code. Actually I took the code from somewhere and There is a point I couldn’t understand. Hope You can help me with that problem.
My code goes like that:
let fruits = ["banana", "melon", "apple", "orange", "peach"];
let returnStatement = fruits.reduce((total, item) => {
return total + ", " + item;
});
console.log(returnStatement);
I am curious at this point why the reduce function doesn’t put the comma at the start of the log statement. Let me show you what I mean.
I expect this statement:
',banana, melon, apple, orange, peach'
I understand that reduce will output just one thing at the end of the process. Here it outputs string.
Why it does not put the comma to the beginning of the string?
>Solution :
The explanation is in the MDN documentation:
If initialValue is specified, that also causes currentValue to be initialized to the first value in the array. If initialValue is not specified, previousValue is initialized to the first value in the array, and currentValue is initialized to the second value in the array.
See the example below, once with an initial value of an empty string, once with your variant:
const fruits =["banana","melon","apple","orange","peach"];
const resultWithoutInitialValue = fruits.reduce((total, item) => {
return total + ", " + item;
});
const resultWithInitialValue = fruits.reduce((total, item) => {
return total + ", " + item;
}, "");
console.log(resultWithoutInitialValue);
console.log(resultWithInitialValue);