A Map in JavaScript is a collection of key-value pairs where both the key and value can be of any data type. Maps allow for efficient lookups, additions, and removals based on the keys.
You can create a Map using the Map
constructor. Here's an example:
// Creating a Map let studentGrades = new Map(); // Setting key-value pairs studentGrades.set("John", "A"); studentGrades.set("Jane", "B"); studentGrades.set("Jim", "C"); // Display the Map console.log(studentGrades); // Map { 'John' => 'A', 'Jane' => 'B', 'Jim' => 'C' }
Here are some useful methods and properties for working with Maps:
// Working with Map methods let studentGrades = new Map(); studentGrades.set("John", "A"); studentGrades.set("Jane", "B"); console.log(studentGrades.get("John")); // 'A' console.log(studentGrades.has("Jane")); // true console.log(studentGrades.size); // 2 studentGrades.delete("Jane"); console.log(studentGrades.has("Jane")); // false studentGrades.clear(); console.log(studentGrades); // Map {}
Maps can also be iterated over using loops or can be transformed. Here is an example of how you can iterate over Map entries:
// Iterating over Map entries let fruitsMap = new Map([ ["Apple", 1], ["Banana", 2], ["Cherry", 3] ]); // Using forEach loop fruitsMap.forEach((value, key) => { console.log(key, value); }); // Output: // Apple 1 // Banana 2 // Cherry 3
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!