javascriptdictionarysetarray.prototype.map

In JavaScript, what is the difference between a map, a Map and a Set?


This concept probably wouldn't confuse me except that two things have the same name and seem to do completely different things. There is the array method aka Array.map() which is basically (I know this is an over simplification) a fancy iterator. I can easily do anything I would with map or filter with a for...loop, it would generally just take more lines of code.

Whereas a Map is similar to a Set. I think Map is more for objects, and it comes with its own crud operations. For that matter, I have no idea why you would choose a Map over a Set and vice versa.

I would love to hear your creative ways of keeping these concepts straight in your own mind. Especially if you created analogies to remember it for yourself, though technical explanations are welcome too!

Thank you!

PS:

I did start by reading MDN on Maps and Array.prototype.map(). I just need more creative ways of thinking about it for it to stick.

Have have been working in JavaScript for a few years and just started learning python... Is a JS Map more like a Python dictionary than an object? I was thinking a dictionary is an object as I have been learning but maybe it is really a Map. I wish JS had chosen different names.


Solution

  • Maps:

    Imagine you're creating a program to store student information. You want to associate each student's ID (unique identifier) with their name and grades. A Map is perfect for this scenario.

    const studentInfo = new Map();
    studentInfo.set(12345, { name: "Alice", grades: [80, 95, 78] });
    studentInfo.set(54321, { name: "Bob", grades: [90, 82, 100] });
    
    console.log(studentInfo.get(12345)); // { name: "Alice", grades: [80, 95, 78] }
    
    // You can use any data type as a key
    studentInfo.set("star", { name: "Star Student", grades: [100, 100, 100] });
    

    Sets:

    Let's say you want to keep track of the unique courses a student has taken. A Set is ideal here, as it only stores unique values and doesn't care about order.

    const coursesTaken = new Set();
    coursesTaken.add("Math");
    coursesTaken.add("English");
    coursesTaken.add("History");
    coursesTaken.add("Math"); // Duplicate is ignored
    
    console.log(coursesTaken); // Set { "Math", "English", "History" }
    
    // Check if a specific course is present
    console.log(coursesTaken.has("Science")); // false