DEV Community

Peter Kang
Peter Kang

Posted on

1

Appreciating Maps in Javascript

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:

Alt Text

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.

Alt Text

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay