Basics

JS Maps

Working with JavaScript Maps

JavaScript Maps store key-value pairs, with methods like set and get.

Introduction to JavaScript Maps

JavaScript Maps are a powerful feature that allow developers to store collections of key-value pairs. Unlike JavaScript objects, Maps can use any data type as a key, offering greater flexibility and performance advantages. This makes them an essential tool for managing collections of data.

Creating a Map

To create a new Map, use the Map constructor. You can initialize a Map without any arguments or pass an iterable, such as an array, to set initial key-value pairs.

Adding and Retrieving Values

To add key-value pairs to a Map, use the set method. To retrieve a value, use the get method by providing the key.

Checking for Keys and Deleting Entries

Maps provide the has method to check if a key exists, and the delete method to remove key-value pairs.

Iterating Over a Map

You can iterate over a Map using the forEach method, or by using a for...of loop with the entries, keys, or values methods.

Map Size and Clearing Maps

Use the size property to get the number of key-value pairs in a Map. The clear method removes all entries from a Map.

Previous
Sets