Learning Path for Programming Journey. Start Now

Everything You Must Know About the JavaScript Map

JavaScript Map

Hackr.io.

Spread the Knowledge

A Map is a collection of elements in JavaScript in which each element is stored as a KV (key, value) pair. It is possible for a JS Map object to hold both objects and primitive values as either the key or the value. Elements in a Map object are iterated in insertion order.

When iterating over the Map object, a key, value pair is returned in the same order as it was inserted i.e. it remembers the original insertion order. The general syntax of creating a JavaScript Map object is:

new Map([it])

Here, it is an iterable object. Values pertaining to the same are stored as key-value pair. If it isn’t specified then the newly created JS Map object will be empty. Any null values are treated as undefined.

Learning JavaScript can take a significant amount of time. If you wish to learn how to hasten the learning process, here’s how to learn JavaScript quickly. So with that covered, let’s advance to a general JavaScript Map code example.

A JavaScript Map Code Example

var map1 = new Map ([[1, 2], [3, 4], [5, 6], [7, 8]]); /*creates a Map object named map1 with integers as both keys and values*/
console.log(map1.size); /* returns the total number of key-value pairs or elements in a Map object*/
var map2 = new Map ([[“Akhil”, “Bhadwal”], [“Vijay”, “Singh”], [“Swapnil”, “Banga”], [“Saurabh”, “Hooda”]]); /*creates a new Map object named map2 with strings as both keys and values*/
console.log(map2.size);
var map3 = new Map ([[“Akhil”, 4], [“Vijay”, 3], [“Swapnil”, 2], [“Saurabh”, 1]]) /* creates a new Map object named map3 containing strings as keys and integers as values*/
console.log(map3.size);

Output:

4
4
4

JavaScript Map Properties

Map.prototype

It represents the prototype for the Map constructor. Moreover, Map.prototype allows the addition of properties to Map objects. In other words, in order to add properties or methods to all Map objects, one can use the constructor’s prototype object.

All Map instances inherit from the Map.prototype property. Map.prototype.constructor returns the function that created a Map instance’s prototype. It is the Map function by default.

Map.prototype.size

Returns the total number of elements i.e. the pairs of key-value in a JavaScript Map object.

General Syntax:

some_map.size

Map.prototype[@@toStringTag]

Has an initial value of Map. Although not enumerable and writable, this property is configurable.

General Syntax:

Map[Symbol.toStringTag]

get Map[@@species]

Used for creating derived objects. The Map[@@species] returns the default Map constructor. In order to change the constructor assignment, subclass constructors might override the property.

General Syntax:

Map[Symbol.species]

JavaScript Map Methods

Map.prototype.set(k, v)

Adds a key (k), value (v) pair to the Map object and returns the Map object.

General Syntax:

some_map.set(k, v);

Example:

var a_map = new Map();
a_map.set(“Akhil”, “Bhadwal”);
a_map.set(“Vijay”, “Singh”);
a_map.set(“Swapnil”, “Banga”);
console.log(a_map.size);

Output:

3

Map.prototype.has(k)

Returns a Boolean value that depends whether a value pertaining to the key is present or not. Returns true if the value is present and false if it is not.

General Syntax:

some_map.has(k);

Example:

var a_map2 = new Map();
a_map2.set("Akhil", 1);
a_map2.set("Vijay", 2);
a_map2.set("Swapnil", 3);
a_map2.set("Saurabh", 4);
console.log(a_map2.has("Akhil"));
console.log(a_map2.has("Lee"));

Output:

true
false

Map.prototype.get(k)

Returns the value pertaining to the input key. In case there is no value associated with the key, returns undefined.

General Syntax:

some_map.get(k);
Example:
var a_map3 = new Map ();
a_map3.set("Twenty Two", 22);
a_map3.set("Twenty Four", 24);
a_map3.set("Forty Six", 46);
console.log(a_map3.get("Twenty Two"));
console.log(a_map3.get("Forty Six"));
console.log(a_map3.get("Seventy Two"));

Output:

22
46
undefined

Map.prototype.delete(k)

Deletes both the key as well as the value pertaining to it from the specified Map object. Returns true if the element was present and deleted, or false if not able to find the value.

General Syntax:

some_map.delete(k);

Example:

var a_map4 = new Map ();
a_map4.set("Y", 25);
a_map4.set("O", 15);
a_map4.set("I", 9);
a_map4.set("B", 2);
console.log(a_map4.size);
console.log(a_map4.delete("O"));
console.log(a_map4.size);
console.log(a_map4.delete("I"));
console.log(a_map4.size);
console.log(a_map4.delete("W"));
console.log(a_map4.size);

Output:

4
true
3
true
2
false
2

Map.prototype.clear()

Removes all the elements i.e. key-value pairs from the specified JavaScript Map object. No parameters are required.

General Syntax:

some_map.clear();

Example:

var a_map5 =  new Map();
a_map5.set(“Twenty Two”, 22);
a_map5.set(“Twenty Four”, 24);
a_map5.set(“Forty Six”, 46);
console.log(a_map5.size);
a_map5.clear();
console.log(a_map5.size);

Output:

3
0

Map.prototype.entries()

Returns a new iterator object containing an array of key-value pair for each element present in the specified Map object in insertion order. Requires no parameter.

General Syntax:

some_map.entries();
Example:
var a_map6 = new Map();
a_map6.set(“Akhil”, “Bhadwal”);
a_map6.set(“Lee”, “Meta”);
var iterator = a_map6.entries();
console.log(iterator.next().value);
console.log(iterator.next().value);

Output:

Array [“Akhil”, “Bhadwal”]
Array [“Lee”, “Meta”]

Map.prototype.keys()

Returns a new iterator object that contains all the keys present in the specified JavaScript Map object in the insertion order. No parameters are required.

General Syntax:

some_map.keys();

Example:

var a_map7 = new Map();
a_map7.set(“First Name”, “Akhil”);
a_map7.set(“Second Name”, “Bhadwal”);
a_map7.set(“Designation”, “Freelance Technical Content Writer”);
a_map7.keys();

Map.prototype.values()

Returns a new iterator object, which contains all values pertaining to the specified Map object in insertion order. No parameters are required.

General Syntax:

some_map.values();

Example:

var a_map8 = new Map();
a_map8.set(“First Name”, “Akhil”);
a_map8.set(“Second Name”, “Bhadwal”);
a_map8.set(“Designation”, “Freelance Technical Content Writer”);
a_map8.values();

Map.prototype.forEach(callbackFn[, thisArg])

Calls callbackFn (the callback function) once each for all the key-value pairs present in the specified Map object in insertion order. The callback function has three parameters:

  1. The element key
  2. The element value
  3. The Map object that needs to be traversed

If a thisArg parameter is also specified then the same will be used as this value for each callback.

General Syntax:

some_map.forEach(callbackFn[, thisArg]);

Example:

function logMapElements(value, key, map) {
  console.log(`m[${key}] = ${value}`);
}
new Map([[“Akhil”, 3], [“Bhadwal”, {}], [“JavaScript Map”, undefined]])
  .forEach(logMapElements);
Output:
"m[Akhil] = 3"
"m[Bhadwal] = [object Object]"
"m[JavaScript Map] = undefined"

Map.prototype[@@iterator]()

Returns a new iterator object containing an array of key-value pair for each element present in the specified Map object in insertion order.

General Syntax:

some_map[Symbol.iterator];

Example:

var a_map10 = new Map();
a_map10.set('Akhil', 'Bhadwal');
a_map10.set(22, 24);
var iterator = a_map10[Symbol.iterator]();
for (let item of iterator) {
console.log(item);

Output:

Array ["Akhil", "Bhadwal"]
Array [22, 24]

JavaScript Map vs JavaScript Objects

A JavaScript Object resembles a JavaScript Map to a great degree. For example, both JS entities allow:

  • Checking whether something is stored at a key or not
  • Deleting keys
  • Retrieving values using keys
  • Setting keys to values

Despite this remarkable similarity, there are several scenarios where using a JavaScript Map is advantageous over a JavaScript Object. These situations arise when:

  • Direct iteration is required. A JS Map object is iterable, unlike the JS Object that requires obtaining the keys and then iterating over them. Obviously, it can be a very time-consuming task if the total number of keys is significantly big
  • Frequent addition and/or removal of key, value pairs are required
  • Maintaining an order for the keys
  • There is a need for storing keys that are neither of the String type nor Symbol type. In a JS Map object, the key can have any type of values

Size of a Map object can easily be gained by using the Map.prototype.size property. However, measuring the size of an Object instance must be done manually.

That’s All!

So that was all about the JavaScript Map objects. Like arrays, Map objects can be cloned. Moreover, they can also be merged with arrays, if required. Hope this article will help you better your understanding of JavaScript Maps.

Consider checking out these best JavaScript tutorials to help you further enhance your JS skills. Have any queries related to JavaScript Map? Let us know via comments! We’ll do our best to help you out.

Related Posts

Your email address will not be published. Required fields are marked *

*