CodeBlanks Logo Icon CodeBlanks

The Map data structure

JavaScript course · Advanced · Lesson 36/100

Learn the ordered key-value Map that accepts any key type.

What is a Map?

A Map is an ordered key-value collection. You create one with new Map() and it keeps insertion order. Unlike a plain object, keys are not limited to strings or symbols; any type works: numbers, objects, even functions.

Use set to add a value and get to read it. The size property tells you how many entries exist. Map stores keys in the order they were added, so iteration order is always consistent.

Map methods

Map has these core methods: set(key, value) adds or updates an entry; get(key) reads the value. has(key) returns true/false for key existence; delete(key) removes an entry. clear() empties the whole Map.

size is a property, not a method; write it without parentheses. If you set the same key a second time, the old value is overwritten; no duplicate key is created.

Exercise A Map with mixed key types

Create a new Map called roles. Add "admin" under key 1, "visitor" under key "guest", and "owner" under a user object key. Then log roles.get(1) with console.log.

Show example solution
const user = { name: "Alex" };
const roles = new Map();
roles.set(1, "admin");
roles.set("guest", "visitor");
roles.set(user, "owner");
console.log(roles.get(1));

Test yourself

  1. Which statement about Map is correct?

    • Keys can only be strings
    • Keys can be objects and functions too
    • It does not preserve insertion order
    • You must count the size yourself
    Show answer

    Keys can be objects and functions too — Correct. Map accepts any key type and preserves insertion order.

  2. Read the value

    const userRoles = new Map();
    userRoles.set(1, "admin");
    const role = userRoles.____(1);
    console.log(role);
    Show answer
    const userRoles = new Map();
    userRoles.set(1, "admin");
    const role = userRoles.get(1);
    console.log(role);
  3. Match the Map methods

    set(key, val)
    Adds a key-value entry
    get(key)
    Returns the value
    has(key)
    Does the key exist?
    size
    How many entries?

All lessons in Advanced