Can someone please explain to me how this code works? [JS]

Hi, I’m new to JavaScript and trying to understand the array methods. I came a cross this code on freeCodeCamp and unable to understand how the brackets work here, especially the empty ones at the end of the code:

var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];

var petCounts = pets.reduce(function(obj, pet){
    if (!obj[pet]) {
        obj[pet] = 1;
    } else {
        obj[pet]++;
    }
    return obj;
}, {});

console.log(petCounts); 

/*
Output:
 { 
    dog: 2, 
    chicken: 3, 
    cat: 1, 
    rabbit: 1 
 }
 */

and if I try to write the same code with arrow functions, I can’t make it work …

var petCounts = pets.reduce((obj, pet) => {
    if (!obj[pet]) {
        obj[pet] = 1;
    } else {
        obj[pet]++;
    }
    return obj;
}, {});

I really appreciate if someone could explain it to me… Thanks a lot…

the reduce method accepts a second argument, which becomes the starting value of the accumulator (otherwise the starting value is the first item in the array)

for why one way it works and the other doesn’t… what do you mean with that? what happens?

Well it works but if I remove the last brackets (because I don’t need the last argument), It doesn’t work anymore… I don’t get the purpose of the last empty brackets…

var petCounts = pets.reduce((obj, pet) => {
    if (!obj[pet]) {
        obj[pet] = 1;
    } else {
        obj[pet]++;
    }
    return obj;
});

you still need it, it is the startinng value of obj, if you don’t put a starting value then the starting value is dog, a string, and you get an error because you can’t change a string in the way your code says

So the starting value is an empty object right ? We create an empty object with the last brackets and then fill it with the if statement ?

it is an empty object because you have set {} as starring value

you can read more about reduce here:

I get it now. Thanks a lot @ilenia . You have been very helpful!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.