Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 14, 2022 08:15 pm GMT

JavaScript - Map

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 datacharacterRoles.set(cypher, "sentinel");// you can chain the method to add multiple entriescharacterRoles.set(raze, "duelist")   .set(omen, "smokes");// check sizecharacterRoles.size // 3// iterablecharacterRoles.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 .

Anime character Itadori


Original Link: https://dev.to/justtanwa/javascript-map-ko1

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To