- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM Node Lists
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
- JavaScript Useful Resources
- JavaScript - Questions And Answers
- JavaScript - Quick Guide
- JavaScript - Functions
- JavaScript - Resources
JavaScript - The Maps Object
A Map object in JavaScript is a collection of key-value pairs where the keys can be of any type, including objects or functions. The order of the map elements is the same as the insertion order of the key-value pairs.
To create a new Map object, you can use the new Map() constructor. You can then add key-value pairs to the map using the set() method. To get the value for a particular key, you can use the get() method. To remove a key-value pair from the map, you can use the delete() method.
Syntax
Following is the syntax to use the Map data structure in JavaScript −
const map = new Map([iterable]);
In the above syntax, we used the 'new' keyword with a Map() constructor to define an instance of the Map.
Parameters
iterable − It is an iterable containing the key-value pairs to initialize the map with elements of the iterable. Also, it is an optional parameter.
The Map class in JavaScript contains a set of built-in methods that allow us to work with Map objects. Here, we have listed the properties and methods of the Map.
Map Properties
Following are the properties of Map object −
Sr.No. | Name & Description |
---|---|
1 |
This property returns the number of elements in this map. |
Map Methods
In the following table, we have listed all the methods of Map object and their description −
Sr.No. | Name & Description |
---|---|
1 |
This method removes all elements from a Map object. |
2 |
This method removes a specified element from a Map object by key. |
3 |
This method returns a new map iterator object that contains the [key, value] pairs. |
4 |
This method executes a callback function once per each key/value pair in a Map object. |
5 |
This method is used to return a specified element from a Map object. |
6 |
This method indicates whether an element with the specified key exists or not. |
7 |
This method returns a new Iterator object that contains the keys for each element in the Map object. |
8 |
This method insert the key-value pair to a Map object. |
9 |
This method returns a new Iterator object that containing values of the Map object. |
JavaScript Map Constructor()
Following is the constructor of Map in JavaScript −
Sr.No. | Name & Description |
---|---|
1 |
To create a Map object. |
Examples
Example: Creating new Map Object
In the example below, we have passed the 2D array containing the key-value pairs as an argument of the Map() constructor.
After that, we traverse the map to get each value of the map and show in the output.
<html> <body> <div> Map elements are: </div> <div id = "output"> </div> <script> const map = new Map([["Apple", 100], ["Banana", 20], ["Orange", 50]]); for (let [key, value] of map) { document.getElementById("output").innerHTML += `${key} : ${value} <br>`; } </script> </body> </html>
Output
After executing the above program, it returns each value of the map.
Map elements are: Apple : 100 Banana : 20 Orange : 50
Example: Inserting key-value pair in the Map
In the example below, we use the set() method to insert the key-value pair in the map. The set() method takes the key as the first argument and the value as the second argument.
<html> <body> <div>After inserting 2 key-value pairs in the map: </div> <div id = "output"> </div> <script> const map = new Map(); map.set("Grapes", 40); map.set("Apples", 50); for (let [key, value] of map) { document.getElementById("output").innerHTML += `${key} : ${value} <br>`; } </script> </body> </html>
Output
After inserting 2 key-value pairs in the map: Grapes : 40 Apples : 50
As we can see in the output, the provided [key-value] pairs have been inserted in the Map object.
Example: Accessing Map Elements
The get() method can be used to access the map elements. Here, we have added elements to the set.
After that, we used the get() method to access the values of the name and RollId keys.
<html> <body> <div id = "output1">Name: </div> <div id = "output2">Roll Id: </div> <script> const map = new Map(); map.set("name", "John"); map.set("rollId", 123); document.getElementById("output1").innerHTML += map.get("name"); document.getElementById("output2").innerHTML += map.get("rollId"); </script> </body> </html>
Output
After executing, it returns all the elements present in the Map object.
Name: John Roll Id: 123
Example: Removing a Map Element
In the example below, we use the delete() method to delete the key-value pair having a key 20.
However, you can also use the clear() method to remove all elements from the map.
<html> <body> <div>Map after deleting the [20,30] key-value pair: </div> <div id = "demo"> </div> <script> const output = document.getElementById("demo"); const map = new Map([[10, 20], [20, 30], [30, 40]]); map.delete(20); // Deleting a [20,30] key-value pair from the map for (let [key, value] of map) output.innerHTML += "Key: " + key + " Value: " + value + "<br/>"; </script> </body> </html>
Output
Map after deleting the [20,30] key-value pair: Key: 10 Value: 20 Key: 30 Value: 40
Example: Size of the Map
In the below code, we used the 'size' property of the Map class to get the total number of key-value pairs in the map.
<html> <body> <p id = "output">Size of the map object is: </p> <script> const map = new Map(); map.set("Grapes", 40); map.set("Apples", 50); document.getElementById("output").innerHTML += map.size; </script> </body> </html>
Output
Size of the map object is: 2
Example: Use object as a key
The map allows developers to use the object as a key. Here, we have defined the laptop object containing two properties.
After that, we set the object as a key and the laptop's price as a value in the map.
<html> <body> <p id = "output">The laptop price is: </p> <script> const map = new Map(); const laptop = { brand: "HP", model: "Pavilion", } map.set(laptop, 100000); document.getElementById("output").innerHTML += map.get(laptop); </script> </body> </html>
Output
The laptop price is: 100000
Map vs. Object in JavaScript
A Map is similar to the Object in JavaScript, but there are some differences which we have explained here −
Basis of Comparison | Map | Object |
---|---|---|
Keys | The map allows you to set the object, function, and other primitive values as a key. | The Object can contain only a string and a symbol as a key. |
Size | You can get the size of the map using the 'size' property. | You need to traverse through the object to determine the size of the object. |
Key comparison | It uses flexible methods to compare the keys. It considers two similar objects with different references different. | It implicitly converts the keys into the string and matches them. |
Iteration | You can use the for...of loop to traverse the map. | You can use the for...in loop to traverse the object properties. |
Performance | The map is slightly slower due to its complex structure. | The object is faster than the map as it only stores keys in the string format. |
Use cases | The map is the better option to use for adding key-value pairs dynamically. | The object is better to use if key-value pairs are static and fixed. |