JavaScript Map

In JavaScript, the Map class is a built-in data structure that allows storing key-value pairs, where keys can be of any data type (including objects, functions, and primitives). Unlike plain JavaScript objects ({}), which only support string or symbol keys, Map maintains the original key types and preserves the order of insertion.

Key Features of JavaScript Map

  1. Key Flexibility: Any data type (objects, arrays, functions, numbers, strings, etc.) can be used as a key.
  2. Order Preservation: Elements in a Map retain their insertion order.
  3. Efficient Key Lookup: Provides better performance for frequent additions and deletions compared to regular objects.
  4. Size Property: The number of key-value pairs can be retrieved directly using the .size property.
  5. Built-in IterationMap supports direct iteration over keys, values, or entries.

Constructor

PropertyDescription
Map()Creates a new Map object.

Static Methods

MethodDescription
Map.groupBy()Groups elements of an iterable into a Map according to a grouping function.

Static Properties

PropertyDescription
Map[Symbol.species]Returns the constructor function used to create derived objects.

Instance Methods

MethodDescription
clear()Removes all elements from a Map object.
delete()Removes a specified element from a Map.
entries()Returns an iterator object with key-value pairs.
forEach()Executes a function for each element in the Map.
get()Returns the value associated with a key in the Map.
has()Checks if a key exists in the Map.
keys()Returns an iterator object with all keys in the Map.
set()Sets a key-value pair in the Map.
values()Returns an iterator object with all values in the Map.
[Symbol.iterator]()Returns an iterator for iterating through key-value pairs.

Instance Properties

PropertyDescription
sizeReturns the number of elements in the Map.