JS Set & Map Flashcards
Set
The Set object lets you store unique values of any type, whether primitive values or object references.
Set objects are collections of values. A value in the Set may only occur once; it is unique in the Set’s collection. You can iterate through the elements of a set in insertion order.
Set.prototype.size
Returns the number of values in the Set object.
Set.prototype.add(value)
Inserts a new element with a specified value in to a Set object, if there isn’t an element with the same value already in the Set.
Set.prototype.clear()
Map.prototype.clear()
Removes all elements from the Set || Map object.
Set.prototype.delete(value)
Removes the element associated to the value and returns a boolean asserting whether an element was successfully removed or not. Set.prototype.has(value) will return false afterwards.
Set.prototype.has(value)
Returns a boolean asserting whether an element is present with the given value in the Set object or not.
What are the main methods of a Set?
.add(value)
.delete(value)
.has(value)
.clear()
Set.prototype.forEach(callbackFn[, thisArg])
Calls callbackFn once for each value present in the Set object, in insertion order. If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackFn.
Set.prototype.values()
Returns a new iterator object that yields the values for each element in the Set object in insertion order.
Map
The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.
Objects vs. Maps
A Map does not contain any keys by default
A Maps keys can be any value (functions, objects, etc)
while an object has to be String or Symbol
The keys in Map are ordered in a simple, straightforward way
The number of items in a Map is easily retrieved from its size property.
A Map is an iterable, so it can be directly iterated.
A Map is better if there are frequent removals or additions
Map.prototype.size
Returns the number of key/value pairs in the Map object.
Map.prototype.get(key)
Returns the value associated to the key, or undefined if there is none.
Map.prototype.has(key)
Returns a boolean asserting whether a value has been associated to the key in the Map object or not.
Map.prototype.set(key, value)
Sets the value for the key in the Map object. Returns the Map object.