Now I'm learning about reduce of Javascript. In below code, I don't understand acc[key] because we can access to properties of objects by using acc["key"] or acc.key . That's what I learned.
but obviously the code below works correctly..why?
const arr = ['Cat', 'Dog', 'Bird', 'Cat']
const result = arr.reduce((acc, key) => {
if (key in acc) {
acc[key]++
} else {
acc[key] = 1
}
return acc
}, {})
console.log(result)
// { Cat: 2, Dog: 1, Bird: 1 }
So as @Alexandro mentioned that key is a string, indeed it is the value or values of the array arr which their type is string. Moreover We know that to access values of an object we follow two ways either square notation (e.g. arr[key]) or dot notation (e.g. arr.key). We perfer to use square notation in case there is a key made or contains space or other special chars.