Sitemap
Neetish Kumar

Neetish Kumar

Developer | 8 years in web & software | Writing about code, life, fitness & growth.

JavaScript Map, Set, WeakMap and WeakSet

7 min readOct 7, 2024

--

  • In JavaScript, Map and Set are built-in data structures introduced in ECMAScript 2015 (ES6).
  • They provide powerful ways to handle collections of values with different properties compared to older data structures like arrays and objects.
  • Objects are used for storing keyed collections.
  • Arrays are used for storing ordered collections.
Press enter or click to view image in full size

1. Map

Definition:

  • A Map is a collection of key-value pairs where both keys and values can be of any data type.
  • Unlike objects, Keys in a Map can be of any type, not just strings or symbols.

Methods and properties are:

  • new Map() – creates the map.
  • map.set(key, value) – stores the value by the key.
  • map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
  • map.has(key) – returns true if the key exists, false otherwise.
  • map.delete(key) – removes the element (the key/value pair) by the key.
  • map.clear() – removes everything from the map.
  • map.size – returns the current element count.
// 🌟 Create a WeakMap
const weakMap = new WeakMap(); // A WeakMap instance

// πŸ“¦ Create a Map with initial key-value pairs
const map = new Map([
['key1', 'value1'],
['key2', 'value2']
]);

// πŸ“ Size: Access the number of key-value pairs in the Map
const sizeOfMap = map.size; // Number of pairs: 2

// βž• set(key, value): Adds a new key-value pair to the Map
map.set('key3', 'value3');
map.set('key4', 'value4');

// πŸ“ Log the Map
console.log(map);
/*
Map(4) {
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
'key4' => 'value4'
}
*/

// πŸ” get(key): Retrieves the value associated with the specified key
const value = map.get('key1'); // 'value1'

// βœ”οΈ has(key): Checks if a key exists in the Map
const exists = map.has('key2'); // true

// ❌ delete(key): Removes a key-value pair from the Map
map.delete('key1'); // Removes 'key1' from the Map

// πŸ—‘οΈ clear(): Removes all key-value pairs from the Map
map.clear(); // Empties the Map

// πŸ”„ Iteration Methods

// 1️⃣ forEach(callback): Executes a callback for each key-value pair
map.forEach((value, key) => {
console.log(`Key: ${key}, Value: ${value}`);
});

// 2️⃣ keys(): Returns an iterator for the keys in the Map
for (const key of map.keys()) {
console.log(`Key: ${key}`);
}

// 3️⃣ values(): Returns an iterator for the values in the Map
for (const value of map.values()) {
console.log(`Value: ${value}`);
}

// 4️⃣ entries(): Returns an iterator for the key-value pairs in the Map
for (const [key, value] of map.entries()) {
console.log(`Key: ${key}, Value: ${value}`);
}

2. Set

Definition:

  • A Set is a collection of unique values. It allows you to store values without duplicates.
  • each value occur only once.
  • Like Maps, the values can be of any data type.

Methods and properties are:

  • new Set([iterable]) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
  • set.add(value) – adds a value, returns the set itself.
  • set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
  • set.has(value) – returns true if the value exists in the set, otherwise false.
  • set.clear() – removes everything from the set.
  • set.size – is the elements count.

Get Neetish Kumar’s stories inΒ yourΒ inbox

Join Medium for free to get updates fromΒ thisΒ writer.

// 🌟 Create a Set
const set = new Set(); // A Set instance

// πŸ“¦ Initialize a Set with initial values
const initializedSet = new Set([1, 2, 3]);

// πŸ“ Size: Access the number of unique values in the Set
const sizeOfSet = initializedSet.size; // Number of unique values: 3

// βž• add(value): Adds a new value to the Set
initializedSet.add(4);
initializedSet.add(2); // Duplicates are ignored

// πŸ“ Log the Set
console.log(initializedSet);
/*
Set(4) {
1,
2,
3,
4
}
*/

// πŸ” has(value): Checks if a value exists in the Set
const hasTwo = initializedSet.has(2); // true
const hasFive = initializedSet.has(5); // false

// ❌ delete(value): Removes a value from the Set
initializedSet.delete(1); // Removes 1 from the Set

// πŸ—‘οΈ clear(): Removes all values from the Set
initializedSet.clear(); // Empties the Set

// πŸ”„ Iteration Methods

// 1️⃣ forEach(callback): Executes a callback for each value
initializedSet.add(1);
initializedSet.add(2);
initializedSet.add(3);

initializedSet.forEach(value => {
console.log(`Value: ${value}`);
});

// 2️⃣ values(): Returns an iterator for the values in the Set
for (const value of initializedSet.values()) {
console.log(`Value: ${value}`);
}

// 3️⃣ entries(): Returns an iterator for the values (same as keys in Set)
for (const [value] of initializedSet.entries()) {
console.log(`Value (entry): ${value}`);
}

// 4️⃣ keys(): Returns an iterator for the values (same as entries)
for (const value of initializedSet.keys()) {
console.log(`Value (key): ${value}`);
}

3. WeakMap

Definition:

  • A WeakMap is a collection of key-value pairs where the keys are objects and the values can be any arbitrary value.
  • Weak References: The keys in a WeakMap are held weakly. This means that if there are no other references to a key object, it can be garbage collected. This prevents memory leaks.
  • Non-iterable: WeakMap does not provide any methods to iterate over its elements. You cannot use methods like forEach, map, or even size.
  • Keys Must Be Objects: Only objects can be used as keys in a WeakMap. Primitive types (like strings or numbers) are not allowed.
  • Key Uniqueness: Each key can only occur once in the WeakMap.

Methods and properties are:

  • set(key, value): Adds or updates an entry with the specified key and value.
  • get(key): Returns the value associated with the key, or undefined if the key does not exist.
  • has(key): Returns a boolean indicating whether the WeakMap contains the specified key.
  • delete(key): Removes the specified key and its associated value from the WeakMap.
// 🌟 Create a WeakMap
const weakMap = new WeakMap(); // A WeakMap instance

// πŸ“¦ Initialize a WeakMap with initial values
const obj1 = {};
const obj2 = {};
const initialEntries= [[obj1, 'Value for obj1'], [obj2, 'Value for obj2']];
const initializedWeakMap = new WeakMap(initialEntries);

// πŸ“ Size: Accessing size is not possible in WeakMap
// const sizeOfWeakMap = initializedWeakMap.size; // This will not work

// βž• set(key, value): Adds a new key-value pair to the WeakMap
const obj3 = {};
initializedWeakMap.set(obj3, 'Value for obj3');
initializedWeakMap.set(obj1, 'Updated value for obj1');
// Update value for obj1

// πŸ“ Log the WeakMap
// (Note: You cannot log WeakMap directly, as it doesn't support iteration)
// However, you can check values using get method
console.log(initializedWeakMap.get(obj1)); // "Updated value for obj1"

// πŸ” has(key): Checks if a key exists in the WeakMap
const hasObj1 = initializedWeakMap.has(obj1); // true
const hasObj3 = initializedWeakMap.has(obj3); // true
const hasObj4 = initializedWeakMap.has({}); // false
// (new object, not in WeakMap)

// ❌ delete(key): Removes a key-value pair from the WeakMap
initializedWeakMap.delete(obj2); // Removes obj2 from the WeakMap

// πŸ—‘οΈ Note: There is no clear method in WeakMap to remove all entries
// WeakMap entries are removed when there are no references to the key

// πŸ”„ Iteration: There are no iteration methods in WeakMap
// Instead, you can only work with individual key-value pairs directly
console.log(initializedWeakMap.get(obj1)); // "Updated value for obj1"
console.log(initializedWeakMap.get(obj3)); // "Value for obj3"

// If you want to check remaining keys,
// you would need to keep track of them yourself
// since WeakMap does not expose any methods for iteration or size

4. WeakSet

Definition:

  • A WeakSet is a collection of objects where each object can only occur once.
  • Weak References: Like WeakMap, the references to the objects in a WeakSet are weak. This means if an object is only referenced in a WeakSet, it can be garbage collected.
  • Non-iterable: WeakSet does not provide methods for iteration or counting elements (no forEach, size, etc.).
  • Only Objects: Only objects can be added to a WeakSet. Primitive values cannot be used.

Methods and properties are:

  • add(value): Adds an object to the WeakSet.
  • has(value): Checks if the object is present in the WeakSet.
  • delete(value): Removes the specified object from the WeakSet.
// 🌟 Create a WeakSet
const weakSet = new WeakSet(); // A WeakSet instance

// πŸ“¦ Initialize a WeakSet with initial values (not directly supported)
const obj1 = {};
const obj2 = {};
const obj3 = {};
const initialObjects = [obj1, obj2]; // Create an array of objects

// Initialize WeakSet
const initializedWeakSet = new WeakSet(initialObjects);

// πŸ“ Size: Accessing size is not possible in WeakSet
// const sizeOfWeakSet = initializedWeakSet.size; // This will not work

// βž• add(value): Adds an object to the WeakSet
const obj4 = {};
initializedWeakSet.add(obj4);
initializedWeakSet.add(obj1); // Adding obj1 again
// (will be ignored if it's already present)

// πŸ“ Log the WeakSet (Note: You cannot log WeakSet directly)
console.log(initializedWeakSet.has(obj1)); // true
console.log(initializedWeakSet.has(obj3)); // false

// πŸ” has(value): Checks if an object exists in the WeakSet
const hasObj1 = initializedWeakSet.has(obj1); // true
const hasObj4 = initializedWeakSet.has(obj4); // true
const hasObj5 = initializedWeakSet.has({}); // false
// (new object, not in WeakSet)

// ❌ delete(value): Removes an object from the WeakSet
initializedWeakSet.delete(obj2); // Removes obj2 from the WeakSet

// πŸ—‘οΈ Note: There is no clear method in WeakSet to remove all entries
// Entries are removed when there are no references to the object

// πŸ”„ Iteration: There are no iteration methods in WeakSet
// You can only work with individual objects directly
console.log(initializedWeakSet.has(obj1)); // true
console.log(initializedWeakSet.has(obj2)); // false

// If you want to check remaining objects,
// you would need to keep track of them yourself
// since WeakSet does not expose any methods for iteration or size

--

--

Written by Neetish Kumar

Developer | 8 years in web & software | Writing about code, life, fitness & growth.