DEV Community

Souvik Guha Roy
Souvik Guha Roy

Posted on

Map and Set in JavaScript

JavaScript offers Map and Set as modern data structures to solve common problems with traditional objects and arrays.

Let’s explore what they are, how they differ, and when to use them.


🧠 What Is a Map?

A Map is a collection of key-value pairs, similar to an object, but with some improvements:

  • Keys can be any type (objects, functions, primitives)
  • Preserves insertion order
  • Built-in methods to get, set, delete, and check entries

βœ… Map Example

```js id="map1"
const map = new Map();

map.set("name", "Rahul");
map.set("age", 22);
map.set(true, "Boolean key");

console.log(map.get("name")); // Rahul
console.log(map.has("age")); // true
console.log(map.size); // 3




---

### πŸ“Š Map Visual



```id="viz1"
Key β†’ Value
"name"  β†’ "Rahul"
"age"   β†’ 22
true    β†’ "Boolean key"
Enter fullscreen mode Exit fullscreen mode

⚑ Map vs Object

Feature Map Object
Key types Any type String / Symbol
Order preservation Yes Not guaranteed
Size property map.size Must compute manually
Iteration Built-in Manual / Object.keys

🧠 What Is a Set?

A Set is a collection of unique valuesβ€”duplicates are automatically removed.

  • Can store any type of value
  • Provides fast lookups and uniqueness checks

βœ… Set Example

```js id="set1"
const set = new Set([1, 2, 3, 2, 1]);

console.log(set); // Set(3) { 1, 2, 3 }
console.log(set.has(2)); // true

set.add(4);
console.log(set); // Set(4) { 1, 2, 3, 4 }




---

### πŸ“Š Set Visual



```id="viz2"
[1, 2, 3, 2, 1] β†’ Set β†’ {1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

⚑ Set vs Array

Feature Set Array
Uniqueness βœ… Unique values ❌ Allows duplicates
Lookup speed Fast Linear search
Methods add, delete, has push, pop, includes

πŸ› οΈ When to Use Map and Set

Use Map when:

  • You need dynamic keys of any type
  • You want ordered key-value storage
  • You need built-in iteration over entries

Use Set when:

  • You want unique values only
  • You need to quickly check existence
  • You want to remove duplicates from an array

πŸ”Ή Removing Duplicates Example

```js id="set2"
const numbers = [1, 2, 3, 2, 4, 3];
const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers); // [1, 2, 3, 4]




---

### πŸ”Ή Map for Counting Occurrences



```js id="map2"
const arr = ["apple", "banana", "apple"];
const countMap = new Map();

arr.forEach(item => {
  countMap.set(item, (countMap.get(item) || 0) + 1);
});

console.log(countMap);
// Map(2) { "apple" => 2, "banana" => 1 }
Enter fullscreen mode Exit fullscreen mode

⚑ Key Takeaways

  • Map β†’ flexible key-value storage, ordered, keys can be any type
  • Set β†’ collection of unique values, fast lookups, removes duplicates easily
  • Solves common limitations of Objects and Arrays

Top comments (0)