Reputation: 894
As a matter of best practices in terms of code readability, Which of the following naming convention should be used while naming arguments of the callback in Array.reduce?
const studentAges= [15,16,14,15,14,20]
Generic
const sum = studentAges.reduce((accumulator,currentValue)=> accumulator +=currentValue,0);
Specific
const sum = studentAges.reduce((sum,age)=> sum+=age,0);
Upvotes: 2
Views: 2896
Reputation: 1442
I sometimes go for a hybrid approach by adding acc
to the accumulator variable name, eg if the result is an array.
In this way you can distinguish between the accumulator in the reduce and the result while still adding meaning to both variable names.
const students = [{
name: 'Joe',
city: 'Wellington'
},
{
name: 'Jane',
city: 'Auckland'
},
{
name: 'Jack',
city: 'Auckland'
},
{
name: 'Jenny',
city: 'Wellington'
},
{
name: 'James',
city: 'Wellington'
}
];
const wellingtonStudents = students.reduce((wellingtonStudentsAcc, student) => {
if (student.city === 'Wellington') {
wellingtonStudentsAcc.push(student);
}
return wellingtonStudentsAcc;
}, []);
console.log(wellingtonStudents);
Upvotes: 0
Reputation: 889
You can call it accumulator, but as the final value of the accumulator is the result of the reduce function, you can also call it result, which makes it more clear that we are looking at the resultant value. i prefer result as that helps make that point otherwise you have to remember that ... the accumulator is what gets returned. you can of course rename the result to whatever you are looking for out of the function too. So guess it depends on what makes it more readable. my pref though is result, because it also gets the result of each iteration.
Upvotes: 1
Reputation: 18525
Please refer to the documentation on the reduce parameters and their order.
First param is the accumulator
followed by currentValue
, currentIndexOptional
and array
.
As far as the naming convention it is up to you and whatever coding standards you follow or prefer.
I personally prefer what you call the generic approach
since it is consistent between the uses ... but again totally personal preference :)
Upvotes: 2