map() and Map are two of the most commonly confused topics in JavaScript because their names are so similar. However, they serve very different purposes. The map() function is used for iterating over arrays, while the Map object is a data structure that helps organize data in a structured way. Let’s dive into these concepts — I’ll do my best to make them easy to understand with clear examples.
map()
The map() function is available for Arrays in JavaScript. It Iterate over each element in an array, modifies them, and returns a new array. map() is mainly used to transform the elements of an array based on the function you provide.
For Example:
const numberList = [1,2,3,4,5,6,7,8,9];
const doubledList = numberList?.map((number)=> number*2)
console.log(doubledList);
console.log(numberList);
// output: [2, 4, 6, 8, 10, 12, 14, 16, 18]
// output: [1,2,3,4,5,6,7,8,9]
/* Here map function created a new array where
every element of the original array is doubled. */
Map
Also known as the Map object, it is a built-in JavaScript feature that lets us store key-value pairs, similar to an object. However, here the catch is that in a Map object a key can be of any type — you can even use an entire object as a key. This is different from objects, where keys are usually limited to strings and symbols.
For Example:
// Create a new Map
const myMap = new Map();
// Use different types as keys
const keyString = "a string"; // using string as a key
const keyObject = {name:'i am a key'}; //using a object as a key
const keyFunction = function() {}; // using a function as a key
// Set values in the Map
myMap.set(keyString, "This is a string key");
myMap.set(keyObject, "This is an object key");
myMap.set(keyFunction, "This is a function key");
// Get values from the Map
console.log(myMap.get(keyString));
// Output: "This is a string key"
console.log(myMap.get(keyObject));
// Output: "This is an object key"
console.log(myMap.get(keyFunction));
// Output: "This is a function key"
console.log(myMap)
/* Output: Map(3) {
'a string' => 'This is a string key',
{ name: 'i am a key' } => 'This is an object key',
[Function: keyFunction] => 'This is a function key'
}*/
Try running this code in your editor to understand it more clearly, but here’s a summary of what’s happening:
- First, we are creating a new Map object like this:
const myMap = new Map();
Then we create some variables and assign them different data types, like a string and an object.
After that, we use the .set() method provided by the Map object to create key-value pairs in the myMap object Like this:
myMap.set(key,value);
- We then access those values using the .get() method:
myMap.get(key)
- In the final console.log, you can see how the values and keys are stored in a similar way to an object within the myMap object. The key difference is that they can all be of different types.
With this I think we’ve clarified the difference between map() and Map, but it might still be challenging to understand where and how to use the Map object in real-life projects. Let’s look at a real-life example to see how the Map object can be useful and how it can be applied in practical situations.
Example: Shopping Cart
To better understand how the Map object can be useful in real-life projects, let’s explore a practical example in an e-commerce application. We’ll look at how a Map can be used to manage a shopping cart.
In a E-commerce Application , you will need to manage items in a shopping cart. Each item will have a unique ID and some other data like product details and its quantity. Now you will have to manage these items like adding or updating them.
Lets see how we can achieve this with Map Object and why it is more effective then other methods.
// Create a new Map for the shopping cart
const cart = new Map();
// Adding Items to the Cart:
/* When a user adds a product to the cart,
you can check if the product already exists in the cart.
If it does, you increase the quantity;
if not, you add it as a new entry. */
function addToCart(product, quantity = 1) {
if (cart.has(product.id)) {
// If product is already in the cart, update the quantity
let cartItem = cart.get(product.id);
cartItem.quantity += quantity;
} else {
// If product is not in the cart, add it
cart.set(product.id, {
name: product.name,
price: product.price,
quantity: quantity
});
}
}
const product1 = { id: 101, name: 'Laptop', price: 999 };
const product2 = { id: 102, name: 'Smartphone', price: 499 };
addToCart(product1, 1);
addToCart(product2, 2);
addToCart(product1, 1); // Adding the same product again
//Accessing Items from the Cart:
//You can easily retrieve the details of a product in the cart using its ID.
console.log(cart.get(101));
console.log(cart.get(102));
// Output: { name: 'Laptop', price: 999, quantity: 2 }
// Output: { name: 'Smartphone', price: 499, quantity: 1 }
/* This output shows that the `Laptop` has been added twice
and `smartphone` is added only once, so the quantity is updated to 2 and 1. */
//Removing Items from the Cart:
function removeFromCart(productId) {
cart.delete(productId);
}
removeFromCart(102); // Removes the 'Smartphone' from the cart
Pretty easy right. I hope this example helps you see how Map
can be used in a real-life frontend development scenario! Let me know if you have any more questions.
Top comments (0)