Knowledgize

Map Object

The Map object in JavaScript is a collection of key-value pairs where the keys can be of any data type. It maintains the order of insertion, allowing for more predictable iteration over the entries. Here are some key features and methods of the Map object:


  • Creation: const map = new Map(); creates an empty map.
  • Adding Entries: map.set(key, value); adds a new key-value pair to the map.
  • Retrieving Values: map.get(key); returns the value associated with the key.
  • Checking Existence: map.has(key); returns true if the key exists in the map.
  • Removing Entries: map.delete(key); removes the key and its associated value from the map.
  • Size: map.size; returns the number of key-value pairs in the map.
  • Iteration: The Map object can be iterated over using methods like forEach, or using for...of loops on map.keys(), map.values(), and map.entries().

Example Usage

const map = new Map(); map.set('name', 'John'); map.set('age', 30); map.set('city', 'New York'); console.log(map.get('name')); // Output: John console.log(map.has('age')); // Output: true console.log(map.size); // Output: 3 map.delete('city'); console.log(map.size); // Output: 2 map.forEach((value, key) => { console.log(key, value); }); // Output: // name John // age 30

Additional Information and Challenges


  1. Maintaining Order:
    • Maps maintain the order of insertion. This makes them predictable when iterating over keys or values, unlike plain JavaScript objects.

  1. Key Types:
    • Keys in a Map can be of any type, including objects, functions, and primitives.

  1. Iteration:
    • You can iterate over the entries in a Map using methods like for...of with map.entries(), map.keys(), and map.values().