Introduction to Maps

Welcome! Today, we'll delve into Maps, a data structure that organizes data as key-value pairs, much like a treasure box with unique labels for each compartment. Imagine dozens of toys in a box. If each toy had a unique label (the key), you could directly select a toy (the value) using the label. No rummaging is required — that's the power of Maps! In this lesson, we'll understand Maps and learn how to implement them in TypeScript.

Maps in TypeScript: Map

TypeScript implements Maps through the Map class. They hold data in key-value pairs with type safety. Let's create a Map, functioning as a catalog for a library:

const libraryCatalog: Map<string, string> = new Map([
    ["book1", "A Tale of Two Cities"],
    ["book2", "To Kill a Mockingbird"],
    ["book3", "1984"]
]);

In this Map, book1, book2, and book3 are keys, while the book titles serve as their respective values. The keys and values both specify types, ensuring type safety. Both keys and values are allowed to be of any type within typescript (primitives, objects, arrays and functions).

Map Operations: Accessing Elements

You can retrieve a book's title using its key straightforwardly with the get() method:

const title1: string | undefined = libraryCatalog.get("book1");
console.log(title1); // Output: "A Tale of Two Cities"

But what happens if you try to access a key that isn't present in the Map? This would return undefined.

const titleNonexistent: string | undefined = libraryCatalog.get("book100");
if (titleNonexistent !== undefined) {
    console.log(titleNonexistent); 
} else {
    console.log("Key not found");
}
// Output:
// Key not found
Map Operations: Verifying the Existence of a Key

As demonstrated, one method to verify the existence of a specific key in the Map is shown above. While this method is valid, it is usually not the most optimal approach. Alternatively, TypeScript provides the built-in has() function that returns a boolean value, offering a more standardized and concise way to check for the presence of a key:

const mapContains: boolean = libraryCatalog.has("book100");

if (mapContains) {
    console.log("Key found");
} else {
    console.log("Key not found");
}
// Output:
// Key not found
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