JS Tutorial



JS MAPS


JavaScript Maps πŸ—ΊοΈ

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.

πŸ’‘ Creating a Map

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' }
  

πŸ”Ž Map Methods and Properties

Here are some useful methods and properties for working with Maps:

  • set(key, value): Adds a key-value pair to the Map
  • get(key): Retrieves the value associated with the key
  • has(key): Checks if the Map contains a specific key
  • delete(key): Removes a key-value pair from the Map
  • size: Returns the number of key-value pairs in the Map
  • clear(): Removes all key-value pairs from the Map
// 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 {}
  

πŸ§‘β€πŸ« Live Example: Map Operations

Map Result will be shown here

πŸ“Œ Use Cases of Maps

  • Storing data where the key-value pairs are needed
  • Efficient lookup of data using keys
  • Associating unique data with an identifier (e.g., user IDs with usernames)
  • Better performance than regular objects when keys are not strings

⚑ Advanced Map Operations

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
  
Note: Maps are especially useful for situations where you need efficient access to key-value pairs and when the keys are not limited to strings (as is the case with objects).

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review