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…