DEV Community

Cover image for Map and Set in JavaScript for Humans
Beto Muniz
Beto Muniz

Posted on

 

Map and Set in JavaScript for Humans

Would you like to hear more about Set and Map objects in JavaScript?

Let's catch up with them on this thread 🧡


Set in JavaScript πŸ‘‡

πŸ“Œ It's not key/value like the Object type. Keys are just values exposed
πŸ“Œ Don't accept duplicated values
πŸ“Œ It's iterable with forEarch method and for...of
πŸ“Œ Conceptually is similar to []

πŸ’‘ Set is useful to remove duplicates on [].


Map in JavaScript πŸ‘‡

πŸ“Œ Allow/preserve any key type. Even objects
πŸ“Œ Don't expose insecure data properties
πŸ“Œ Iterate with forEarch method and for...of
πŸ“Œ Stay the insertion order doesn't matter the type

πŸ’‘ Prefer Map instead of {} for client-side data manipulation.


Thoughts on Map, Set, {}, and [] in JavaScript πŸ‘‡

πŸ“Œ Each has a specific usage in JS
πŸ“Œ Use {} for data traffic from the server.
πŸ“Œ Set helps apply omit, diff, etc. on []
πŸ“Œ Map return size. {} don't return size

πŸ—£ There's not a silver bullet. Use them carefully.


πŸ˜‰ Hope that you now understand better such useful objects on JavaScript, they are highly valuable, and master them will make you a better JavaScript Developer.

πŸ’Œ Also, don't miss content like this signing my newsletter.

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!