HashMap in JavaScript
Anushka rangari
2 min read
Table of contents
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
Method | Description |
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 |
size | returns 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
Objects | Maps |
Have default keys that could collide with your own keys. | Don't have default keys |
doesn't have size property | have size property |
not directly iterable | directly 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 maps | usage- The map accepts any key type |
0
Subscribe to my newsletter
Read articles from Anushka rangari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by