JavaScript Map Methods

Essential methods for working with JavaScript Maps

🔧 Map Methods Overview

JavaScript Maps come with powerful built-in methods that make it easy to add, remove, and manipulate key-value pairs. These methods provide a clean API for map operations.


// Basic Map methods example
const userMap = new Map();
userMap.set('name', 'Alice');
userMap.set('age', 25);
console.log(userMap.get('name')); // "Alice"
console.log(userMap.has('age'));  // true
                                    

Output:

Alice
true

Core Map Methods

set(key, value)

Adds or updates a key-value pair

map.set('key', 'value');
📥

get(key)

Retrieves value by key

const value = map.get('key');

has(key)

Checks if key exists

if (map.has('key')) { }
🗑️

delete(key)

Removes a key-value pair

map.delete('key');

🔹 Adding and Updating Values

The set() method is used to add new entries or update existing ones:

const productMap = new Map();

// Adding new entries
productMap.set('laptop', 999);
productMap.set('mouse', 25);
productMap.set('keyboard', 75);

// Updating existing entry
productMap.set('laptop', 899); // Price reduced

// Chaining set methods
productMap.set('monitor', 299).set('speakers', 49);

console.log(productMap.get('laptop'));  // 899
console.log(productMap.size);           // 5

Output:

899
5

🔹 Retrieving and Checking Values

Use get() to retrieve values and has() to check existence:

const colorMap = new Map([
    ['red', '#FF0000'],
    ['green', '#00FF00'],
    ['blue', '#0000FF']
]);

// Getting values
console.log(colorMap.get('red'));     // "#FF0000"
console.log(colorMap.get('yellow'));  // undefined

// Checking existence
console.log(colorMap.has('blue'));    // true
console.log(colorMap.has('purple'));  // false

// Safe value retrieval
const yellowColor = colorMap.has('yellow') 
    ? colorMap.get('yellow') 
    : '#FFFF00';
console.log(yellowColor); // "#FFFF00"

Output:

#FF0000
undefined
true
false
#FFFF00

🔹 Removing Values

Use delete() to remove specific entries or clear() to remove all:

const taskMap = new Map([
    ['task1', 'Buy groceries'],
    ['task2', 'Walk the dog'],
    ['task3', 'Finish project']
]);

console.log('Before deletion:', taskMap.size); // 3

// Delete specific entry
const deleted = taskMap.delete('task2');
console.log('Deleted successfully:', deleted); // true
console.log('After deletion:', taskMap.size);  // 2

// Try to delete non-existent key
const notDeleted = taskMap.delete('task4');
console.log('Non-existent deleted:', notDeleted); // false

// Clear all entries
taskMap.clear();
console.log('After clear:', taskMap.size); // 0

Output:

Before deletion: 3
Deleted successfully: true
After deletion: 2
Non-existent deleted: false
After clear: 0

🔹 Iteration Methods

Maps provide several methods for iterating over entries:

const scoreMap = new Map([
    ['Alice', 95],
    ['Bob', 87],
    ['Charlie', 92]
]);

// Using forEach
console.log('Using forEach:');
scoreMap.forEach((score, name) => {
    console.log(`${name}: ${score}`);
});

// Using for...of with entries()
console.log('\nUsing for...of:');
for (const [name, score] of scoreMap) {
    console.log(`${name} scored ${score}`);
}

// Getting all keys
console.log('\nAll names:', Array.from(scoreMap.keys()));

// Getting all values
console.log('All scores:', Array.from(scoreMap.values()));

Output:

Using forEach:
Alice: 95
Bob: 87
Charlie: 92

Using for...of:
Alice scored 95
Bob scored 87
Charlie scored 92

All names: Alice,Bob,Charlie
All scores: 95,87,92

🔹 Practical Example: User Management

Here's a practical example using multiple Map methods:

class UserManager {
    constructor() {
        this.users = new Map();
    }
    
    addUser(id, userData) {
        this.users.set(id, userData);
        return this;
    }
    
    getUser(id) {
        return this.users.get(id);
    }
    
    updateUser(id, updates) {
        if (this.users.has(id)) {
            const current = this.users.get(id);
            this.users.set(id, { ...current, ...updates });
            return true;
        }
        return false;
    }
    
    removeUser(id) {
        return this.users.delete(id);
    }
    
    getAllUsers() {
        return Array.from(this.users.values());
    }
    
    getUserCount() {
        return this.users.size;
    }
}

// Usage example
const manager = new UserManager();

manager.addUser(1, { name: 'Alice', email: '[email protected]' })
       .addUser(2, { name: 'Bob', email: '[email protected]' });

console.log('User count:', manager.getUserCount());
console.log('User 1:', manager.getUser(1));

manager.updateUser(1, { age: 25 });
console.log('Updated user 1:', manager.getUser(1));

Output:

User count: 2
User 1: {name: "Alice", email: "[email protected]"}
Updated user 1: {name: "Alice", email: "[email protected]", age: 25}

🧠 Test Your Knowledge

Which method is used to add a new key-value pair to a Map?