This article explains the concepts of maps in javascript in details with some real world example. Introduction to Maps in javascript with a simple example.
Maps data structure was introduced in Javascript ES6 to solve some problem that comes when we use javascript objects.
Maps are key/value pair data structure in javascript. maps are similar to javascript objects except the fact that it can contain any data type as key.
Maps key can be of any data type, it can be string,number or an object itself.
there are other different characteristics also between object and Maps.
1let data = new Map()23let val = {4 id: 1,5}67console.log(data instanceof Object)89console.log(val instanceof Map)
So, the output will be like,
map can be created using keyword new with Map.
1let data = new Map()
this is an initialization of map which is stored in the variable data.
you can add items to Map using a method set() which basically sets the value to key.
1data.set(1, {2 address: {3 country: "India",4 postal: 123456,5 },6})7data.set(2, {8 address: {9 country: "US",10 postal: 123456,11 },12})1314console.log(data)
So, it sets the value to data with key 1 and 2.
you can get the value from map using the key in Map data structure. Map uses method get() which returns the value from the key.
1console.log(data.get(1))23console.log(data.get(2))
you can delete an item from map using key. delete() is a method used to delete an item from map.
1console.log(data.delete(2))2console.log(data)
you can delete all items in map using the method clear().
1//deleting all items in the map2data.clear()
you can iterate over all the keys in the map using map.keys()
1//iterating over map keys2for (const k of data.keys()) {3 console.log(k)4}
Similarly, you can iterate over all the values in the map using map.values().
1//iterating over map values2for (const k of data.values()) {3 console.log(k)4}
So, it will output like,
1//iterating over map key,value pairs2for (const [k, v] of data) {3 console.log(k, v)4}
WeakMap is also a Map except the fact that it has garbage collection. if a key lost the reference, then particular value from the WeakMap will be garbage collected.
Let's see an example to understand the concept,
1let user = {2 name: "Steve",3}45let weakMap = new WeakMap()6weakMap.set(user, "check")78user = null // overwrite the reference910console.log(weakMap) //it will be removed from the memory
can you guess what is the output of it?.
Here, we have user variable which is basically a key for weakmap. if you null the user variable, weakMap lost the reference for key.
it will be garbage collected automatically in WeakMap.
To sum up, These are all the concepts of Maps and WeakMaps in Javascript.
How to Run MongoDB as a Docker Container in Development
No spam, ever. Unsubscribe anytime.