Set and WeakSet in JavaScript
Learn about the Set and WeakSet data structures in JavaScript, their features, use cases, and performance considerations.
Last updated: 2024-01-03Introduction to Set and WeakSet
Set and WeakSet are two powerful data structures introduced in ECMAScript 2015 (ES6). They provide efficient ways to store unique values and offer unique features that make them suitable for various programming scenarios.
Set in JavaScript
A Set is a collection that stores unique values of any type, whether primitive values or object references.
Creating a Set
You can create a Set using the Set constructor:
const mySet = new Set();
You can also initialize a Set with an iterable:
const mySet = new Set([1, 2, 3, 4, 5]);
Set Methods
Sets provide several useful methods:
add(value)
: Adds a new element to the Set.has(value)
: Checks if a value exists in the Set.delete(value)
: Removes the specified element from the Set.clear()
: Removes all elements from the Set.
Example:
const mySet = new Set();
mySet.add(1);
mySet.add('hello');
mySet.add({name: 'John'});
console.log(mySet.has(1)); // Output: true
console.log(mySet.has('world')); // Output: false
mySet.delete(1);
console.log(mySet.has(1)); // Output: false
mySet.clear();
console.log(mySet.size); // Output: 0
Set Properties
size
: Returns the number of elements in the Set.
Iterating over a Set
Sets are iterable and provide several methods for iteration:
values()
: Returns an iterator of values.keys()
: Same as values() for Set objects.entries()
: Returns an iterator of [value, value] pairs.forEach()
: Executes a provided function for each value in the Set.
Example:
const mySet = new Set([1, 2, 3]);
for (const value of mySet) {
console.log(value);
}
mySet.forEach(value => {
console.log(value);
});
Use Cases for Set
- Removing duplicate values from an array
- Maintaining a collection of unique items
- Efficient lookup for large sets of data
- Implementing mathematical set operations (union, intersection, difference)
WeakSet in JavaScript
A WeakSet is a collection of objects only, where references to the objects are held weakly. This means that if there are no other references to an object stored in the WeakSet, it can be garbage collected.
Creating a WeakSet
You can create a WeakSet using the WeakSet constructor:
const myWeakSet = new WeakSet();
WeakSet Methods
WeakSets provide a subset of Set methods:
add(value)
: Adds a new object to the WeakSet.has(value)
: Checks if an object exists in the WeakSet.delete(value)
: Removes the specified object from the WeakSet.
Example:
const myWeakSet = new WeakSet();
const obj1 = {};
const obj2 = {};
myWeakSet.add(obj1);
myWeakSet.add(obj2);
console.log(myWeakSet.has(obj1)); // Output: true
console.log(myWeakSet.has({})); // Output: false
myWeakSet.delete(obj2);
console.log(myWeakSet.has(obj2)); // Output: false
WeakSet Properties
WeakSets do not have a size
property or any methods for iterating over their contents.
Use Cases for WeakSet
- Tagging objects without modifying them
- Storing a collection of DOM elements
- Implementing object-based "sets" that don't prevent garbage collection
- Detecting circular references in object graphs
Differences between Set and WeakSet
-
Value types:
-
Set: Can store any type of values (primitives and objects).
-
WeakSet: Can only store object references.
-
Value references:
-
Set: Strongly references its values.
-
WeakSet: Weakly references its values, allowing them to be garbage collected.
-
Iterability:
-
Set: Iterable and provides methods for iteration.
-
WeakSet: Not iterable and doesn't provide methods for accessing its values.
-
Size property:
-
Set: Has a
size
property. -
WeakSet: Does not have a
size
property. -
Use cases:
-
Set: General-purpose storage of unique values.
-
WeakSet: Specialized use cases involving object references and memory management.
Performance Considerations
- Sets generally have better performance for checking the existence of an item compared to arrays.
- WeakSets can help prevent memory leaks in scenarios where you need to associate data with objects without preventing garbage collection.
- For small collections, the performance difference between Set and Array may be negligible.
Best Practices
- Use Set when you need to maintain a collection of unique values.
- Use WeakSet when you need to store object references without preventing garbage collection.
- Prefer Set over Array when you frequently need to check for the existence of items.
- Use WeakSet for tagging objects or implementing object-based sets that don't prevent garbage collection.
Frequently Asked Questions
- Q: Can I use primitive values in a WeakSet? A: No, WeakSet only accepts objects as values.
- Q: How can I check the size of a WeakSet? A: WeakSet doesn't provide a size property or a method to check its size due to its weak reference nature.
- Q: Are Set and WeakSet thread-safe? A: JavaScript is single-threaded, so thread safety is not an issue. However, if you're using Web Workers, each worker has its own global scope and memory.
- Q: Can I use Set and WeakSet in older browsers? A: Set and WeakSet are supported in all modern browsers. For older browsers, you may need to use a polyfill or transpile your code.
- Q: How do I convert a Set to an array? A: You can use the spread operator or Array.from():
const mySet = new Set([1, 2, 3]);
const array = [...mySet];
// or
const array = Array.from(mySet);
Additional Resources
-
MDN Web Docs:
-
JavaScript.info:
-
Books:
-
"You Don't Know JS" series by Kyle Simpson
-
"Eloquent JavaScript" by Marijn Haverbeke
-
Online Courses:
-
JavaScript: The Advanced Concepts on Udemy
-
Deep JavaScript Foundations, v3 on Frontend Masters
-
GitHub Repositories:
-
You-Dont-Need-Lodash-Underscore - Examples of Set and WeakSet usage in native JavaScript
-
Articles:
-
ES6 In Depth: Collections by Jason Orendorff
-
Understanding Set and WeakSet in JavaScript by DigitalOcean