Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
JavaScript provides built-in data structures that make working with collections more convenient and efficient. Let's examine Set, Map, WeakSet and WeakMap.
Set is a collection of unique values where each value can appear only once.
add(value) — adds value.delete(value) — removes value.has(value) — checks value presence.clear() — clears collection.size — returns number of elements.const set = new Set();
set.add(1);
set.add(2);
set.add(2); // Ignored, because 2 is already in collection
console.log(set.has(1)); // true
console.log(set.size); // 2
set.delete(1);
console.log(set); // Set { 2 }
Map is a collection of key-value pairs where keys can be of any type.
set(key, value) — adds key-value pair.get(key) — returns value by key.delete(key) — removes pair by key.has(key) — checks key presence.clear() — clears collection.size — returns number of elements.const map = new Map();
map.set('name', 'John');
map.set({ id: 1 }, 'Object');
console.log(map.get('name')); // John
console.log(map.size); // 2
map.delete('name');
console.log(map); // Map { { id: 1 } => 'Object' }
WeakSet is a collection that stores only objects. These objects are weakly referenced, allowing garbage collector to remove them if there are no other references.
add(value) — adds object.delete(value) — removes object.has(value) — checks object presence.const weakSet = new WeakSet();
let obj = { name: 'John' };
weakSet.add(obj);
console.log(weakSet.has(obj)); // true
obj = null; // Object will be removed from WeakSet by garbage collector
WeakMap is a collection of key-value pairs where keys can only be objects and values can be anything. Keys are weakly referenced, allowing garbage collector to remove objects if there are no more references.
set(key, value) — adds key-value pair.get(key) — returns value by key.delete(key) — removes key-value pair.has(key) — checks key presence.const weakMap = new WeakMap();
// Create object
let user = { name: "John" };
// Add object as key and value
weakMap.set(user, "User data");
console.log(weakMap.get(user)); // "User data"
// Remove reference to object
user = null;
// Object will be removed from WeakMap by garbage collector
WeakMap Limitations:
WeakMap is suitable for storing data associated with objects that can be removed by garbage collector. For example, for attaching metadata to DOM objects.