JavaScript Maps Tutorial

What is a JavaScript Map

  1. A JavaScript Map is a data structure that allows you to store key-value pairs.
  2. Each key in a Map can only occur once, and the keys can be of any data type, including objects and functions.
  3. Maps are widely used in JavaScript for various tasks, such as data storage, caching, and maintaining key-value associations.
  4. A social media application could use a map to store the user's friends list.
  5. The keys would be the friends' user IDs, and the values would be the friends' names. This would allow the application to quickly and easily retrieve the names of the user's friends without having to search through an entire database.
  6. An e-commerce application could use a map to store the prices of products in different currencies.

Creating a Map

  1. You can create a Map in JavaScript using the Map constructor:
const myMap = new Map();

Adding Key-Value Pairs

  1. You can add key-value pairs to a Map using the set method
const myMap = new Map();
myMap.set('name', 'John');
myMap.set('age', 30);
myMap.set('city', 'New York');

console.log(myMap); //Output: Map(3) { 'name' => 'John', 'age' => 30, 'city' => 'New York' }

Map Initialization

  1. You can initialize a Map with key-value pairs in its constructor.
const myMap = new Map([
    ['name', 'Bob'],
    ['age', 25],
    ['city', 'London']
  ]);

Getting Values

  1. You can retrieve values from a Map using the get method.
console.log(myMap.get('name')); // Output: 'John'
console.log(myMap.get('age'));  // Output: 30

Checking for Key Existence

  1. You can check if a key exists in a Map using the has method.
console.log(myMap.has('name'));   // Output: true
console.log(myMap.has('country')); // Output: false
    

Deleting Key-Value Pairs

  1. You can remove key-value pairs from a Map using the delete method:
myMap.delete('age');
console.log(myMap.get('age')); // Output: undefined
    

Getting the Size

  1. You can find the number of key-value pairs in a Map using the size property
console.log(myMap.size); // Output: 2

Iterating Through a Map

  1. You can iterate through the key-value pairs of a Map using the forEach method.
myMap.forEach((value, key) => {
    console.log(`${key}: ${value}`);
});

/* Output: 
name: John
age: 30
city: New York
*/
  

Clearing a Map

  1. You can remove all key-value pairs from a Map using the clear method
myMap.clear();
console.log(myMap.size); // Output: 0

Using Functions as Keys

  1. You can also use functions as keys
const myFunction = () => console.log('Hello');
myMap.set(myFunction, 'A function');
console.log(myMap.get(myFunction)); // Output: 'A function'

Complete Map Example in JavaScript

  1. This example shows how JavaScript maps can be used to store and manage product data, track items in a shopping cart, and calculate the total price of the items in the cart, without using classes.
// Create a map of products
const productsMap = new Map();
productsMap.set(1, { id: 1, name: "T-shirt", price: 20 });
productsMap.set(2, { id: 2, name: "Jeans", price: 30 });
productsMap.set(3, { id: 3, name: "Shoes", price: 40 });

// Get a product from the map
const product = productsMap.get(1); // { id: 1, name: 'T-shirt', price: 20 }

// Iterate over the map and display the products in the console
for (const [id, product] of productsMap) {
    console.log(`${id}: ${product.name}`);
}

// Output:
// 1: T-shirt
// 2: Jeans
// 3: Shoes
    
// Create a shopping cart map
const shoppingCartMap = new Map();

// Add an item to the shopping cart
shoppingCartMap.set(1, { quantity: 1 }); // Add a T-shirt to the shopping cart

// Get the total price of the items in the shopping cart
const totalPrice = 0;
for (const [productId, item] of shoppingCartMap) {
    const product = productsMap.get(productId);
    totalPrice += product.price * item.quantity;
}

console.log(`Total price: ${totalPrice}`); // 20