JavaScript Set and Map


Set and Map are ES6 (ES2015) features used to store collections of data. Unlike plain objects and arrays, they offer unique capabilities that are useful in many real-world applications.



Set in JavaScript – Unique Value Collection


What is a Set?

A Set is a collection of unique values. No duplicates allowed.


Example:

const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2);  // Duplicate, ignored
mySet.add("apple");

console.log(mySet);

Output

Set(3) { 1, 2, 'apple' }


Set Methods

Method Description
add(value) Adds a value to the set
delete(value) Removes a value
has(value) Returns true if value exists
clear() Removes all elements
size Returns the number of elements


Usage Example:

console.log(mySet.has(2));     // true
mySet.delete(2);
console.log(mySet.has(2));     // false
console.log(mySet.size);       // 2


Iterating a Set

mySet.forEach(value => console.log(value));


Use Case: Removing Duplicates from an Array

const numbers = [1, 2, 2, 3, 4, 4];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);  // [1, 2, 3, 4]


Map in JavaScript – Key-Value Collection


What is a Map?

A Map stores key-value pairs, similar to objects, but with better control and flexibility.

Example:

const myMap = new Map();
myMap.set("name", "Alice");
myMap.set("age", 25);
myMap.set("isAdmin", true);

console.log(myMap);

Output

Map(3) { 'name' => 'Alice', 'age' => 25, 'isAdmin' => true }


Map Methods

Method Description
set(key, value) Adds or updates a key-value pair
get(key) Gets the value by key
has(key) Checks if a key exists
delete(key) Removes a key
clear() Clears the entire map
size Returns the number of key-value pairs


Usage Example:

console.log(myMap.get("name"));  // Alice
console.log(myMap.has("age"));   // true
myMap.delete("isAdmin");
console.log(myMap.size);         // 2


Iterating a Map

myMap.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});


Map vs Object

Feature Map Object
Key Types Any (object, function, etc.) Strings and Symbols only
Order Preserves insertion order Not guaranteed
Iterable Yes Partially
Size Property .size Use Object.keys().length
Performance Better for frequent updates Simpler for static data