I've been loving using Maps in JS lately for a variety of purposes. A simple one is to go through an iterable and count the occurrence of each of the items.
For example, I'll have a array of grocery items and a new instance of a Map to store those items and their respective number of occurrences:
Pretty cool! The loop iterates through the grocery list and checks if it already exists in the Map. If it doesn't, it'll create a new key-value pair with the item as key and 1 as its value. If it does, then it'll increment the existing value.
This was how I'd been going about it for a while, then I realized we can make this much more concise.
We'll remove any conditionals, and go straight to using the set method. The item will be set as a key from the get-go, and in the value parameter, we'll set up the get method to get the associated value.
We've set a default value as 0 by utilizing the logical OR operator, so if that get value returns undefined (aka it doesn't exist), it'll have something to fall back on. Lastly, it'll increment by 1 to set the value as 1 if the item doesn't exist, or it'll increment an existing value.
I do feel like the first approach is a bit more intuitive, however knowing how default values and logical operators, well, operate would be so 🔥 with the second approach.
Top comments (0)