DEV Community

Discussion on: Enhance your JS Skill by using the correct array method

Collapse
 
jonrandy profile image
Jon Randy 🎖️

you need to init this accumulator

This is incorrect, you can omit the initial value for the accumulator. If you do this, the accumulator will be automatically initialised to the first item in the array, and the reduce will continue from the next item. Your example can therefore be written more efficiently as:

const items = [1, 2, 3, 4]

const sum = items.reduce((accumulator, currentValue) => {
   return accumulator += currentValue
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codeoz profile image
Code Oz

Hey thanks for comment, in fact you but it's really not adice to not init your accumulator value!

I edtied the post about this fact thanks!

Collapse
 
jonrandy profile image
Jon Randy 🎖️

The ability to have the accumulator automatically initiated like this is a part of JS and allows for more efficient code. Telling people not to use it is bad advice. The same advice applies as per my other comment - how do you expect developers to improve at JS if there is an insistence on treating them as children who will not understand more than basic code. 'Readable' code is subjective, and should not come at the price of less efficient code, and the misleading of people who are learning.

Collapse
 
mariamemeel profile image
Mora Emeel

I was about to write this comment