
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use of Map in JavaScript
Map
Map holds key value pairs and remembers the actual insertion order of the keys. Map allows to store only a unique value.
syntax
new Map([iterable])
Case-1: Absence Of Map
In the absence of Map, since javascript object endorses only one key object, If we provide multiple keys only the last one will be remembered. In the following example despite providing many keys such as a and b only b is remembered and displayed as output.So to eliminate this drawback "Map" came in to existence in javascript.
Example
<html> <body> <script> const x = {}; const a = {}; const b = { num:3 } x[a] = "a"; x[b] = "b"; document.write(JSON.stringify(x)); </script> </body> </html>
Output
{"[object Object]":"b"}
case-2: Presence Of Map
As we know from the definition that Map is going to remember the actual insertion order of keys it displays all the key and value pair such as '{}' as a key and 'a' has a value etc. as shown in the output.
Example
<html> <body> <script> const a = {}; const b = { num:3 } const map = new Map(); map.set(a, "a").set(b, "b"); for(let[key, value] of map.entries()){ document.write(JSON.stringify(key, value)); // displaying key using Map document.write((key, value)); // displaying value using Map } </script> </body> </html>
Output
{}a {"num":3}b
Advertisements