Science Knowings: JavaScript Course For Social Media

Map Object

Meet the Map Object

Stepping away from Set Object, let's dive into the realm of Map, another fundamental data structure in JavaScript.

Map vs. Object: Key Differences

Map and Object share similarities in storing key-value pairs, but there are key differences to note.

  • Keys: Map uses any type as keys, including objects and arrays, while Objects only accept strings or symbols as keys.
  • Order: Map preserves insertion order, meaning you can iterate over key-value pairs in the sequence they were added. Objects don't guarantee order.
  • Extensibility: Maps are not extensible, meaning you can't add new properties or methods to them. Objects inherit from the Object prototype, allowing for extension.

Creating a Map Object

Creating a Map is simple:

const myMap = new Map();

You can also initialize a Map with key-value pairs:

const myMap = new Map([['key1', 'value1'], ['key2', 'value2']]);

Adding Key-Value Pairs to a Map

To add key-value pairs, use the set() method:

myMap.set('key3', 'value3');

Getting Values from a Map

Retrieve values using the get() method:

const value = myMap.get('key1');

Checking for Keys in a Map

Use the has() method to check if a key exists:

if (myMap.has('key2')) { ... }

Deleting Key-Value Pairs from a Map

Remove key-value pairs with the delete() method:


Looping Through a Map

Iterate over Map entries using forEach():

myMap.forEach((value, key) => { ... });

Map Methods

set()Adds or updates a key-value pair.
get()Returns the value associated with a key.
has()Checks if a key exists in the Map.
delete()Removes a key-value pair from the Map.
sizeReturns the number of key-value pairs in the Map.
clear()Removes all key-value pairs from the Map.
keys()Returns an iterator of the keys in the Map.
values()Returns an iterator of the values in the Map.
entries()Returns an iterator of the key-value pairs in the Map.

Use Cases for Maps

Maps are useful in various scenarios:

  • Caching: Store frequently accessed data in a Map for faster retrieval.
  • Data Management: Organize complex data structures with key-based access.
  • Object Properties: Use Maps as properties of objects to store additional information.
  • Custom Data Structures: Create your own custom data structures using Maps.

Next Topic: Typed Arrays (Why are they used? Follow us to learn!)

Next up, let's dive into Typed Arrays, a powerful tool for efficient data handling in JavaScript. Follow us to unlock the potential of Typed Arrays.