Updated July 10, 2023
Introduction to Javascript Map Function
The Map is a standard built-in object used to hold elements in a key-value pair, and it also recollects the primordial insertion sequence of the keys. All types of values, such as objects, primitive values, functions, etc., can be used as either a key or a value. The Javascript Map Function object iterates in the original insertion sequence. If for each loop is used to iterate over the Map, an array of key-value pairs will result in each iteration.
Syntax:
new Map( [itr] )
Here it is an array or any other iterable in the form of a key-value pair. (For example, an array named arr of 2 values like arr = [[‘a’, ‘value of a’], [‘b’, ‘value of b’]] ). The new Map created will include these key-value pair values.
Map Instances
All the Map instances are inherited from Map.prototype
Properties:
- prototype.size: This property will return the number of key-value pairs present at the instance in the Map.
- prototype.constructor: This property will return the function that created the Map prototype. It is the Map function by default.
Methods:
- prototype.get( key ): This method will return the associated value for the key or undefined if the key is not present in the Map.
- prototype.set( key, value ): This method will insert the key-value pair in the Map if the key is not present; otherwise, update the key with the value in the Map.
- prototype.clear( ): This method will delete all the key-value pairs from the Map object.
- prototype.enteries( ): This method will return a new iterable object with an array of all the key-value pairs in the same insertion order as Map.
- prototype.delete( key ): This method will return true if the key exists in the Map object and delete it from the Map otherwise, it will return false when the key is absent in the Map.
- prototype.has( key ): This method will provide a boolean result indicating whether a key-value pair exists in the Map or not.
- prototype.keys( ): This method will return an iterable object containing an array of all the keys in the Map object.
- prototype.values( ): This method will return an iterable object containing an array of all the values in the Map object.
Examples of Javascript Map Function
The examples of the javascript map function are given below:
1. Using the Map Object
Code:
var mapObj= new Map()
var stringKey = 'Hello'
var objKey= {}
var funcKey = function () { }
// setting the values
mapObj.set(stringKey, "value for stringKey")
mapObj.set(objKey, "value for objKey")
mapObj.set(funcKey, "value for funcKey")
console.log(mapObj.size) // 3
// getting the values
console.log(mapObj.get(stringKey)) // "value for stringKey"
console.log(mapObj.get(objKey)) // "value for objKey"
console.log(mapObj.get(funcKey)) // "value for funcKey"
console.log(mapObj.get('Hello')) // "value for stringKey"
// because stringKey === 'Hello'
console.log(mapObj.get({})) // undefined, because objKey !== {}
console.log(mapObj.get(function () { })) // undefined, because funcKey !== function () {}
Output:
2. Using NaN as a Map Key
Code:
var mapObj = new Map()
mapObj.set(NaN, 'not a number')
console.log(mapObj.get(NaN)) // "not a number"
var somethingelse = Number('abc')
console.log(mapObj.get(somethingelse)) // "not a number"
Output:
3. Using forEach () loop to iterate over a Map
Code:
var mapObj = new Map()
mapObj.set(0, 'zero')
mapObj.set(1, 'one')
mapObj.forEach(function (value, key) {
console.log(key + ' -> ' + value)
})
for (var [key, value] of mapObj.entries()) {
console.log(key + ' -> ' + value)
}
for (var [key, value] of mapObj) {
console.log(key + ' -> ' + value)
}
for (var key of mapObj.keys()) {
console.log(key)
}
for (var value of mapObj.values()) {
console.log(value)
}
Output:
4. Merging two Maps
Code:
var fMap = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
])
var sMap = new Map([
[1, 'uno'],
[2, 'dos']
])
// Merge two maps. The last repeated key wins.
// Spread operator essentially converts a Map to an Array
var outputMap = new Map([...fMap, ...sMap])
console.log(outputMap.get(1)) // uno
console.log(outputMap.get(2)) // dos
console.log(outputMap.get(3)) // three
var mergeMap = new Map([... fMap, ...sMap, [1,'ek']])
console.log(mergeMap.get(1)) // ek
Output:
Maps and Objects Compared
Maps and Objects are usually similar in some aspects, such as objects also have key-value pairs. The users can also retrieve values associated with a key, delete key values, update them, and determine whether a specific key has an associated value. That is why people prefer to use objects more frequently than maps, but there are also significant differences between them; let’s check them below:
- The keys of Objects can only be a String or Symbol, whereas Maps can accept any value as the key, such as functions, primitives, arrays, etc.
- You can use the size method to determine the size of a Map. However, with Objects, you must manually calculate their properties.
- When using a Map, the keys will always be ordered based on their insertion. However, with an Object, the keys are not ordered.
- To iterate on an Object, we have to get the keys of it, whereas a Map is directly iterable.
- A Map can perform better in cases with frequent addition and deletion of the key-value pairs.
Conclusion
Maps become handy when handling data in a key-value manner and regularly updating it. Key equality in Maps is based on the sameValueZero algorithm. The code compares NaN as equal to NaN, which is incorrect, and the === operator governs the comparison of all other values.
Setting the object properties for a Map also works. It’s important to address this condition to avoid any confusion that may arise.
var mapObj = new Map()
mapObj['abc'] = 'abcd'; // Results in Ambigous Map
MapObj.set('abc','abcd'); // Right way to set key-value pair
Recommended Articles
We hope that this EDUCBA information on “Javascript Map Function” was beneficial to you. You can view EDUCBA’s recommended articles for more information,