Map Data Structure in JavaScript
In this tutorial, we will learn about how to use and when to use Map in JavaScript.
Maps in Javascript
What is Map?
Maps is JavaScript's' new data structure which is introduced in ES6.
Map is a data strcture that we can use to map values to keys, so just like an object data is stored in key value pairs in maps.
Creating Map:
const programming = new Map();
Methods:
set():
programming.set('name', 'javascript');
We can also chain set method like below:
programming
.set('tags', ['js', 'jquery', 'typescript'])
.set('version', 'es6')
Get():
We can access values using keys:
programming.get('name');//javascript
has():
Check value exist or not
programming.has('categories'); // true
Delete():
programming.delete('version');
Clear():
Remove all the elementes
programming.clear();
Difference between Maps and Objects:
- A Map is similar to Object, but any value can be used as key in maps, but keys in objects are only Strings and Symbols
- The key-value pairs in Map maintains the insertion order, whereas Object don’t.
- You can get the size of the Map, but we don’t have a built-in method to get size in Object
- Maps are iterable, whereas an Object is not iterable by-default.
- Maps have additional methods not available to normal object