Map can store key-value pairs, where key and value can be of any type. It is able to remember original insertion order of keys in map. Map in javascript is an object.
How to Create a Map
- with new Map()
- with Map.set()
with new Map()
Map() constructor is used to create Map.
<script>
const mobile = new Map([
["company","Motorola"],
["Color","Black"],
["Price",10000],
]);
</script>
with Map.set()
Besides Map() constructor, to create a new map, it has set(), which accepts two parameters, one is key and second one is its value.
<script>
const mobile = new Map();
mobile.set("Company","Motorola");
mobile.set("Color","Black");
mobile.set("Price","10000");
</script>
How to get Map values
get() method of map is used to get value of a key in map.
<script>
const mobile = new Map([
["Company","Motorola"],
["Color","Black"],
["Price",10000],
]);
document.write(mobile.get("Price"));
</script>
Check the length or size of Map
To check number of elements or length of a map, it has size property which returns map size.
<script>
const mobile = new Map([
["Company","Motorola"],
["Color","Black"],
["Price",10000],
]);
document.write(mobile.size); // Returns number of elements
</script>
Clear or remove all Map elements
To remove all elements, map has clear() method.
<script>
const mobile = new Map([
["Company","Motorola"],
["Color","Black"],
["Price",10000],
]);
mobile.clear(); // clears all elements
</script>
Delete given Map element with key
To delete given key and value in a map, it has delete() method. Below example helps you to understand how to delete map element.
<script>
const mobile = new Map([
["Company","Motorola"],
["Color","Black"],
["Price",10000],
]);
mobile.delete("Color"); // Delete given elements
</script>
Check given key exists or not in map
has() is used to check, weather a key in a map exists or not. If exists, it returns true, false if it doesn’t.
<script>
const mobile = new Map([
["Company","Motorola"],
["Color","Black"],
["Price",10000],
]);
document.write(mobile.has("Company")); // Returns true if exists
</script>
Map methods
new Map() | Create a new Map object |
set() | Add or insert new key-value. |
get() | Get a value from Map for a given key |
clear() | Remove all Map element at once |
delete() | Delete given value from Map |
has() | Checks value is present in set or not |
values() | Returns iterator object with Map values |
keys() | Works same as values(), Returns iterator object with values in a Map. |
entries() | Return [value, value] from Map . |
forEach() | Calls the function for each element of set |
size | Returns map length or number of elements present in a given Map. |