Introduction to Maps in JavaScript

Introduction to Maps

Hi, and welcome! Today, we'll explore 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 required — that's the power of Maps! Today, we'll understand Maps and learn how to implement them in JavaScript.

Maps in JavaScript: Map

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

const libraryCatalog = 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. It's important to remember that the keys should be of a type that supports hashing and equality comparison. Examples include String, Number, and Boolean. The values can be of any type.

Map Operations: Accessing Elements

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

const title1 = 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 = libraryCatalog.get("book100");
if (titleNonexistent !== undefined) {
    console.log(titleNonexistent); 
} else {
    console.log("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, JavaScript 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 = libraryCatalog.has("book100");

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