The following four data structures are new in ECMAScript 6: Map
, WeakMap
, Set
and WeakSet
.
The Map object is a simple key/value map. Any value (both objects and primitive values) may be used as either a key or a value.
Basic usage
var colorsMap = new Map();
colorsMap.set('redKey','red');
console.log(colorsMap.get('redKey')); // red
console.log(colorsMap.has('redKey')); // true
colorsMap.delete('redKey');
console.log(colorsMap.has('redKey')); // false
Map size and clear:
var map = new Map([
[ 1, 'one' ],
[ 2, 'two' ],
[ 3, 'three' ]
]);
console.log(map.size); // 3
map.clear();
console.log(map.size); // 0
Iterating Maps with for..of
var map = new Map();
map.set(1, "One");
map.set(2, "two");
map.set(3, "three");
for(let [key,value] of map) {
console.log(`Key: ${key} Value: ${value}`);
}
Objects Vs maps
Objects allow you to set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key.
Map objects, however, have a few more advantages that make them better maps.
- The keys of an Object are Strings, where they can be of any value for a Map.
- You can get the size of a Map easily while you have to manually keep track of size for an Object.
- The iteration of maps is in insertion order of the elements.
- An Object has a prototype, so there are default keys in the map. (this can be bypassed using map = Object.create(null)).
These three tips can help you to decide whether to use a Map or an Object:
- Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.
- Use maps in case if there is a need to store primitive values as keys because object treats each key as a string whether it's a number value, boolean value or any other primitive value.
- Use objects when there is logic that operates on individual elements.