Can you confirm that “user” is the element (currentValue) being processed?
If “obj” is the accumulator, I’m uncertain how it’s being used here obj[user.name]. Because to me, that looks like an object’s key is being set.
In addition, I find that whole like appears to be the declaration of a key/value pair for an object.
Finally, at the end there it has a {} being passed in as what appears to be the index parameter of the reduce function. That seems super odd to me based on my understanding of an index (the key in an array).
Can anyone chime in and set me straight? I have a feeling I’m way off here…
Thanks for the explanation! That really helped me understand the components. And then running through it as @miku86 suggested crystallized it in my mind.
The parameters as used in the exercise in my initial question are:
1. accumulator = obj
2. currentValue = user
3. index = //this is not set
4. array = //this is not set
5. initialValue = {} //an empty object
When the code is running, obj is first declared as an empty object by the initialValue.
Then obj has its first property passed in as John: 34.
This value is returned on the next line, but because .reduce uses a callback function, it continues iterating through the users array.
Next Amy: 20 is added on to obj and so on until the end of the array whereupon the value of obj is assigned to usersObj and console logged.
In case anyone else reading this was wondering why/how obj[user.name] = user.age; avoids overwriting itself, that is done by setting an object property using the bracket notation.