Introduction

Welcome to our JavaScript data structures revision! Today, we will delve deeply into JavaScript Maps. Much like a bookshelf, Maps allow you to quickly select the book (value) you desire by reading its label (key). They are vital to JavaScript for quickly accessing values using keys and for efficient key insertion and deletion. So, let's explore JavaScript Maps for a clearer understanding of these concepts.

JavaScript Maps

Our journey starts with JavaScript Maps, a pivotal data structure that holds data as key-value pairs. Imagine storing your friend's contact info in such a way that allows you to search for your friend's name (the key) and instantly find their phone number (the value).

class PhoneBook {

    constructor() {
        // An empty Map
        this.contacts = new Map();
    }

    addContact(name, phoneNumber) {
        // Method to add a contact
        this.contacts.set(name, phoneNumber);
    }

    getPhoneNumber(name) {
        // Method to retrieve contact's phone number, or undefined if it's not in contacts
        return this.contacts.get(name);
    }
}

// Create a PhoneBook instance
const phoneBook = new PhoneBook();

// Add contacts
phoneBook.addContact("Alice", "123-456-7890");
phoneBook.addContact("Bob", "234-567-8901");
console.log(phoneBook.getPhoneNumber("Alice")); // Output: "123-456-7890"
console.log(phoneBook.getPhoneNumber("Bobby")); // Output: undefined

In the above code, we create a PhoneBook class that uses a Map to store contacts. As you can see, Maps simplify the processes of adding, modifying, and accessing information with unique keys.

Operations in Maps

JavaScript Maps enable a variety of operations for manipulating data, such as setting, getting, deleting key-value pairs, and more. Understanding these operations is crucial for efficient data handling in JavaScript.

To add or update entries in a Map, you use the set method. If the key exists, the value is updated; if not, a new key-value pair is added. This flexibility allows for dynamic updates and additions to the Map without needing a predefined structure.

The get method is used to retrieve the value associated with a specific key. It provides a safe way to access values, as attempting to access a non-existent key simply returns undefined.

Checking if a key exists in the Map can be done using the has method. This method returns a boolean value—true if the key exists in the Map, otherwise false. This is particularly useful for conditionally handling data based on its existence in the Map.

Deleting an entry is done using the delete method followed by the key. This operation removes the specified key-value pair from the Map, which is essential for managing the contents of the Map actively.

The size property provides the number of key-value pairs present in the Map. This is especially useful when you need to know the total count of entries in the Map.

Let’s see how these operations work in the context of a TaskManager class:

class TaskManager {

    constructor() {
        // Initialize with an empty Map
        this.tasks = new Map();
    }

    addUpdateTask(taskName, status) {
        // Add a new task or update an existing task
        this.tasks.set(taskName, status);
    }

    getTaskStatus(taskName) {
        // Retrieve the status of a task; Returns "Not Found" if the task does not exist
        return this.tasks.get(taskName) !== undefined ? this.tasks.get(taskName) : "Not Found";
    }

    deleteTask(taskName) {
        // Removes a task using its name
        if (this.tasks.has(taskName)) {
            this.tasks.delete(taskName);
        } else {
            console.log(`Task '${taskName}' not found.`);
        }
    }

    getTaskCount() {
        // Returns the number of tasks in the TaskManager
        return this.tasks.size;
    }
}

// Test the TaskManager class
const myTasks = new TaskManager();
myTasks.addUpdateTask("Buy Milk", "Pending");
console.log(myTasks.getTaskStatus("Buy Milk"));  // Output: Pending
myTasks.addUpdateTask("Buy Milk", "Completed");
console.log(myTasks.getTaskStatus("Buy Milk"));  // Output: Completed

myTasks.deleteTask("Buy Milk");
console.log(myTasks.getTaskStatus("Buy Milk"));  // Output: Not Found

myTasks.addUpdateTask("Clean House", "In Progress");
console.log(myTasks.getTaskCount());  // Output: 1

This example showcases how to leverage Map operations in JavaScript to effectively manage data by adding, updating, retrieving, deleting entries, and checking the number of entries through a simulated Task Manager application.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal