HashMap in JavaScript

what is HashMap ?

  • HashMap is a data Structure that can store data in key value pairs/

  • HashMap remembers the original insertion order of keys .

  • HashMap has a property that represents the size of the map.

Map Methods

MethodDescription
new Map()creates a new Map object
set()set the value of a key
get()gets the value for a key
clear()removes all the elements
delete()removes a map element
has()checks if the key exists
for Each()callback function for each key /value pair
entries()returns an object with key, value pairs in a map
values()returns the values
keys()returns the keys
sizereturns the number of map elements
let names=new Map([
    ["nush",500],
    ["matoe",1000]
]) //creating new Map  
names.set("gracy",2000) //adds a new key value pair
console.log(names.get("nush")) //gets value for the given key 
console.log(names.has("nushs")) //checks if they given key is present
for(let i of names.keys()){
 console.log(i)
} //print the keys 
for(let i of names.values()){
    console.log(i)
   } //prints the value
console.log(names.size) //returns the size of the map 
names.forEach((value,key)=>{
 console.log(`key :${key} , value:${value}`)
}) //for each method

Difference Between Object and Maps

ObjectsMaps
Have default keys that could collide with your own keys.Don't have default keys
doesn't have size propertyhave size property
not directly iterabledirectly iterable
Usage - where we need simple structure to store data and the type of keys needed is either an integer, strings or symbols. JSON supports objects and not mapsusage- The map accepts any key type