It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 82 – JavaScript Maps

In this lesson, we will explore Maps in JavaScript—what they are, how to create and manipulate them, and when to use them over regular objects.


What is a Map?

A Map is a collection of key-value pairs, just like an object. However, Maps offer some advantages over objects:

  • Keys can be any type (not just strings or symbols).
  • Maps maintain the insertion order of elements.
  • Maps have a size property.
  • Maps provide built-in methods for iteration, addition, deletion, etc.

Creating a Map

const myMap = new Map();

Or initialize with key-value pairs:

const capitals = new Map([
  ["Ghana", "Accra"],
  ["France", "Paris"],
  ["Japan", "Tokyo"]
]);

Basic Map Methods

set(key, value)

Adds a new key-value pair.

capitals.set("Germany", "Berlin");

get(key)

Retrieves the value for a given key.

console.log(capitals.get("France")); // Paris

has(key)

Checks if a key exists.

console.log(capitals.has("Japan")); // true

delete(key)

Deletes a key-value pair.

capitals.delete("Ghana");

clear()

Removes all key-value pairs.

capitals.clear();

size

Returns the number of key-value pairs.

console.log(capitals.size);

Iterating through Maps

for (let [country, city] of capitals) {
  console.log(`${country} ? ${city}`);
}

You can also use:

  • map.keys() – iterate over keys
  • map.values() – iterate over values
  • map.entries() – iterate over key-value pairs

When to Use Maps?

Use Maps when:

  • You need key-value pairs with non-string keys.
  • You need to maintain insertion order.
  • You need frequent additions and deletions.

Try Your Hand

  1. Create a Map of usernames to email addresses.
  2. Add a new entry to it.
  3. Check if a specific username exists.
  4. Loop through the Map and log each entry.

Summary

  • Maps are great for flexible and efficient key-value storage.
  • They work well when the keys are not just strings.
  • Useful methods: set, get, has, delete, clear, size, and iteration helpers.