Open In App

Map in JS

Last Updated : 18 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A JavaScript Map holds key-value pairs and similar to Hash Map or Dictionary in other languages.

  • Preserves the original insertion order.
  • It supports any type, including objects and primitives, as keys or values. This feature allows for efficient data retrieval and manipulation.
  • JavaScript Maps internally use Hashing that makes time complexities of operations like search, insert and delete constant or O(1) on average. It is useful for operations like counting frequencies, maintaining dictionaries, and storing key based objects.
  • Only Unique Keys are allowed, if we insert the same key with a different value, it overwrites the previous one.
  • It is always recommended to use Maps over Objects when we have frequent insert and delete operations as maps perform better.
JavaScript
let m = new Map([
    ["k1", "v1"],
    ["k2", "v2"],
    ["k3", "v3"]
]);
console.log(m);

Output
Map(3) { 'k1' => 'v1', 'k2' => 'v2', 'k3' => 'v3' }

Recommended Links:

Creating a Map

Map() constructor allows two ways to create a Map in JavaScript.

  • Passing an Array to new Map() [Please see the above code]
  • Create a Map and use Map.set() [Please see the below code]
JavaScript
let m = new Map();
m.set("k1", "v1");
m.set("k2", "v2");
m.set("k3", "v3");

// This will overwrite the
// previous key value pair as
// key is already present
m.set("k3", "v4");

console.log(m);

Output
Map(3) { 'k1' => 'v1', 'k2' => 'v2', 'k3' => 'v4' }

Methods / Properties of JavaScript Map

  • set(key, val) : Adds or updates an element with a specified key and value.
  • get(key) : Returns the value associated with the specified key.
  • has(key) : Returns a boolean indicating whether an element with the specified key exists.
  • delete(key) : Removes the element with the specified key.
  • clear(): Removes all elements from the Map.
  • size: Returns the number of key-value pairs in the Map.

This example explains the use of Map methods like has(), get(), delete(), and clear().

JavaScript
let m = new Map();

m.set("k1", "v1");
m.set("k2", "v2");
m.set("k3", "v3")
    .set("k4", "v4")
    .set("k5", "v5");

console.log("m has k4 ? " + m.has("k4"));
console.log("m has k6 ? " + m.has("k6"));

console.log("value for k4 " + m.get("k4"));
console.log("value for k6 " + m.get("k6"));

console.log("delete k4 " + m.delete("k4"));
console.log("delete k6 " + m.delete("k6"));

m.clear();
console.log(m);

Output
m has k4 ? true
m has k6 ? false
value for k4 v4
value for k6 undefined
delete k4 true
delete k6 false
Map(0) {}

Advantages of Map

Map object provided by ES6. A key of a Map may occur once, which will be unique in the map’s collection. There are slight advantages to using a map rather than an object.

  • Unique Keys: A key can occur only once, ensuring uniqueness within the collection.
  • Security: No default keys are stored; only what is explicitly added, making it safer.
  • Flexible Key Types: Any value (object, function, etc.) can be used as a key.
  • Order: Maintains the order of entry insertion.
  • Size Property: The size property makes it easy to retrieve the number of elements.
  • Performance: Operations on Maps can be performed efficiently.
  • Serialization and Parsing: Custom serialization and parsing support using JSON.stringify() and JSON.parse() methods.

JavaScript Maps provide a robust mechanism for handling key-value pairs, offering unique advantages over plain objects. With their secure, flexible, and efficient operations, Maps are an essential tool for modern web development. Coupled with the map() method for arrays, JavaScript offers versatile ways to manipulate and iterate over data collections effectively.

JavaScript Map – FAQs

What is a Map in JavaScript?

A Map is a built-in object that allows you to store key-value pairs. Unlike regular objects, which only allow string or symbol keys, a Map can have keys of any type, including objects, functions, and primitives.

How do you create a Map?

You can create a Map using the Map constructor.

Example: const myMap = new Map();

How do you add key-value pairs to a Map?

You can add key-value pairs to a Map using the set() method. This method takes two arguments: the key and the value.

Example: myMap.set(‘key’, ‘value’);

How do you get a value from a Map?

You can retrieve a value from a Map using the get() method. This method takes one argument, the key, and returns the associated value.

Example: myMap.get(‘key’);

How do you check if a key exists in a Map?

You can check if a key exists in a Map using the has() method. This method returns true if the key exists, and false otherwise.

Example: myMap.has(‘key’);

How do you remove a key-value pair from a Map?

You can remove a key-value pair from a Map using the delete() method. This method takes one argument, the key, and removes the associated key-value pair.

Example: myMap.delete(‘key’);



Next Article

Similar Reads

three90RightbarBannerImg
  翻译: