Hey 👋, hope y'all are well! Lets talk about Map
in JavaScript!
Map 🗺️
Map in JavaScript (JS) allow you to store information/data using a key-value relationship. But wait... isn't that the same as an Object
in JS? Map does return Object
when you use typeof
but it is not exactly the same. They are very similar in nature but they have distinct differences that determine their uses.
So what are these distinct differences? Well, if you are using Object
the keys must be a String
or Symbol
datatype whereas the keys in Map
can be any datatype including Function
and Object
. Another thing is that to find the size of an Object
you must do it manually, e.g. grabbing all the keys using Object.keys()
then counting the length. But, Map
has a property .size
which return the size of the Map
.
Additionally, Objects are not directly iterable while with Maps you can.
Example: Map
comes with its own methods and you can see some of them below.
const cypher = {name: "Cypher", color: "white"};
const raze = {name: "Raze", color: "orange"};
const omen = {name: "Omen", color: "blue"};
const characterRoles = new Map(); // create an empty Map.
// add new data
characterRoles.set(cypher, "sentinel");
// you can chain the method to add multiple entries
characterRoles.set(raze, "duelist")
.set(omen, "smokes");
// check size
characterRoles.size // 3
// iterable
characterRoles.forEach((role, char) => {
console.log(char.name + " is a " + role)
});
// Cypher is a sentinel
// Raze is a duelist
// Omen is a smokes
As I continue to learn more about Data Structure and Algorithm, I learnt that Map
is JavaScript's equivalent to a Hashmap and have been using them to solve some problems.
Summary
To summarise, Map allow you to store data as key-value pairs that are not limited to String
(or Symbol
) datatype as keys. It also give you the ability to directly iterate through the data. Additionally, Maps have it's own properties and methods that you can use to add, access, edit, and delete the data in the collection.
Thank you for reading this short post, please leave a comment if you want to add information or give feedback 😀.