The TypeScript map is a novel data structure introduced in the ES6 version of JavaScript. It enables the storage of data in key-value pairs while preserving the sequence of key insertion, akin to other programming languages. In a TypeScript map, any value can be utilized as either a key or a value.
Creating a Map in TypeScript
Syntax:
var map = new Map<string, number> ();
Example:
A Map is instantiated using the Map constructor as demonstrated below, and we can also include type annotations to enhance type safety.
Example
const userRoles = new Map<string , string>();
userRoles.set("admin", "Full Access");
userRoles.set("editor", "Edit Access");
userRoles.set("viewer", "Read-Only Access");
console.log("User Roles are",userRoles);}
</string>
Output:
User Roles are Map(3) {
'admin' => 'Full Access',
'editor' => 'Edit Access',
'viewer' => 'Read-Only Access'
}
Clarification: In this instance, a new Map named userRoles has been established, which holds a pairing of string keys and string values. Additionally, various data types may be utilized as keys. The userRoles map consists of three key-value pairs. The console.log function outputs the map object to the console.
Map methods
The TypeScript map methods are listed below:
1. map.set(key, value)
The set function is utilized to insert or modify an element within a Map object, requiring a key and a value as inputs. If the specified key is already present, the value will be updated accordingly. Consequently, this method returns the modified map, allowing for additional operations to be performed through method chaining on the returned value.
Syntax:
map.set(key, value);
Example
const studentMarks = new Map<string , number>();
studentMarks.set("Alice", 85);
studentMarks.set("Bob", 92);
studentMarks.set("Charlie", 78);
console.log("Student Marks are",studentMarks);
</string>
Output:
Student Marks are Map(3) {
'Alice' => 85,
'Bob' => 92,
'Charlie' => 78
}
Explanation:
To dynamically insert key-value pairs, the set method can be utilized.
2. map.get(key)
It yields the value associated with the specified key in a Map. If the key does not exist, it returns undefined.
Syntax:
map.get(key);
Example
const userRoles = new Map<number , string>();
userRoles.set(1, "Admin");
userRoles.set(2, "Editor");
userRoles.set(3, "Viewer");
console.log("Role is",userRoles.get(2));
console.log("Role is",userRoles.get(4));
</number>
Output:
Role is Editor
Role is undefined
Explanation:
A notable prevalent technique is get, which retrieves the values linked to a specific key. It is essential to verify the existence of the key beforehand. To avoid errors caused by attempting to access undefined values, we initially evaluate the outcome from get with has(key).
3. map.has(key)
The has function provides a boolean result indicating whether a Map contains the given key.
Syntax:
map.has(key);
Example
const stock = new Map<string , number>();
stock.set("Apple", 120);
stock.set("Banana", 200);
console.log(stock.has("Apple"));
console.log(stock.has("Mango"));
</string>
Output:
true
false
Explanation:
This becomes especially beneficial when you intend to initiate an action upon finding a key. It enables you to verify securely prior to executing functions like get or delete.
4. map.delete(key)
The delete function removes a key from a Map object along with its associated value. It returns true if the key was located and successfully deleted; otherwise, it returns false.
Syntax:
map.delete(key);
Example
const countries = new Map<string , string>();
countries.set("IN", "India");
countries.set("US", "United States");
countries.set("UK", "United Kingdom");
console.log(countries.delete("US"));
console.log(countries.delete("FR"));
console.log(countries);
</string>
Output:
true
false
Map(2) { 'IN' => 'India', 'UK' => 'United Kingdom' }
Explanation:
The delete function yields a non-negative integer and serves the purpose of removing undesirable entries while also playing a role in memory management. This functionality is particularly advantageous in scenarios like caching, where it is necessary to remove outdated entries.
5. map.size
The size property indicates the total count of key-value pairs present in a Map. It is a property that can only be read.
Syntax:
map.size
Example
const books = new Map<string , string>();
books.set("978-0131103627", "The C Programming Language");
books.set("978-0201616224", "The Pragmatic Programmer");
console.log(books.size);
</string>
Output:
Explanation:
This feature is useful for determining the count of elements contained in the map at any given moment. It is well-suited for implementing conditional logic, managing pagination, or monitoring growth within a memory-based cache.
6. map.clear
The clear function eliminates all entries from a Map object. After invoking this method, the Map will be devoid of any elements.
Syntax:
map.clear();
Example
const products = new Map<number , string>();
products.set(101, "Laptop");
products.set(102, "Smartphone");
console.log("Product Size is",products.size);
products.clear();
console.log("Product Size is",products.size);
</number>
Output:
Product Size is 2
Product Size is 0
Explanation:
The clear will be useful when you need to make a new map to reuse again. It is especially useful in situations such as:
- Clearing cache
- Resetting state
- Restarting a session
It is a superior operation, which means be careful when you use it to clear a map.
| SN | Methods | Descriptions |
|---|---|---|
1. |
map.set(key, value) | It is used to add entries in the map. |
2. |
map.get(key) | It is used to retrieve entries from the map. It returns undefined if the key does not exist in the map. |
3. |
map.has(key) | It returns true if the key is present in the map. Otherwise, it returns false. |
4. |
map.delete(key) | It is used to remove the entries by the key. |
5. |
map.size() | It is used to return the size of the map. |
6. |
map.clear() | It removes everything from the map. |
Iterating Map Data
We can traverse the keys, values, or entries of a map using the 'for...of' loop. The subsequent example illustrates this concept more effectively.
Example
let ageMapping = new Map();
ageMapping.set("Rakesh", 40);
ageMapping.set("Abhishek", 25);
ageMapping.set("Amit", 30);
//Iterate over map keys
for (let key of ageMapping.keys()) {
console.log("Map Keys= " +key);
}
//Iterate over map values
for (let value of ageMapping.values()) {
console.log("Map Values= " +value);
}
console.log("The Map Enteries are: ");
//Iterate over map entries
for (let entry of ageMapping.entries()) {
console.log(entry[0], entry[1]);
}
Output:
Map Keys= Rakesh
Map Keys= Abhishek
Map Keys= Amit
Map Values= 40
Map Values= 25
Map Values= 30
The Map Enteries are:
Rakesh 40
Abhishek 25
Amit 30
TypeScript Map vs. Object
In some fundamental ways, a Map differs from a standard JavaScript object :
- Key Flexibility: The key of an object can only be a string or a symbol, but a Map can have a key of any data type, such as a number, an object, a boolean, an array, and a function.
- Order Preservation: The Map object preserves the order of its key-value entries. It's crucial when we care about the order of our elements.
- Size Tracking: Map Size property is a direct number so it returns the number of elements in the map which is very easy to get but with the object, count manipulation has to be done.
- Iteration Support: Maps are iterable by default. You will be able to iterate through them just like a for loop or use methods like forEach, keys, values, and entries.
Advantages of Typescript Map
- Permits the use of any data type as a key
While standard objects are limited to strings or symbols for keys, the Map structure permits the use of any data type as keys, including objects, arrays, functions, or numbers. This feature provides developers with greater flexibility when dealing with intricate data structure patterns.
- Maintains insertion order
A Map preserves the sequence of the entries as they are added. This feature is useful in scenarios where the order of data is significant, such as when presenting elements in the chronological order of their reception or logging.
- Direct access to size
The .size attribute allows for a straightforward and efficient way to determine the number of entries in a Map. In contrast, when working with objects, we must take extra steps to calculate the size, such as utilizing Object.keys.
- Enhanced efficiency for regular updates
In situations where you frequently need to add, remove, or search for key-value pairs, maps offer greater efficiency compared to objects, particularly in applications where performance is crucial.
Disadvantages of TypeScript Map
- is not suitable for direct JSON serialization.
In JSON, instances of Map cannot be directly utilized with stringify, implying that they must first be transformed into a primitive object or an array. This requirement complicates scenarios involving API calls or interactions with persistence.
- No dot notation for key access
The Map object does not permit the use of dot notation for retrieving values, necessitating the use of methods such as get and set for all operations, which may seem unusual to some programmers.
- Somewhat increased memory consumption
In the case of small datasets, it could consume significantly more memory than standard objects. This could be an important factor in environments where memory efficiency is crucial.
Frequently Asked Questions (FAQ)
- Is it possible for a Map in TypeScript to contain duplicate keys?
No, as a Map cannot contain duplicate keys. If you assign a value to a key that is already present, it will replace the current value.
- Is a Map quicker than an object?
In standard objects, keys are exclusively strings, and to utilize a number as a key, it must first be converted to a string. However, in a Map, keys can be of any type, which makes Map more efficient than standard objects when you frequently add, remove, and search for keys, especially with large data sets.
- What occurs if I employ an object as a key in a Map?
Utilizing an object as a key is permissible and functions correctly in a Map; however, objects are compared based on their reference rather than their structure. Consequently, two distinct instances containing the same data are regarded as separate keys.
- Is Map compatible with all browsers?
Indeed, the Map object was introduced in ECMAScript 2015 (ES6) and is supported by all modern browsers and JavaScript engines.