Prior to the introduction of Maps in ES6, objects were generally used to hold key-value pairs. Maps have advantages over objects when creating hash maps because:
size
property.Note: an object can be iterated over as well, but not without the trickery of first converting it to an array, or checking to see if the property being iterated over belongs to it and not a prototype.
set()
- add/update a key-value entry.
var movie = new Map();
movie.set('name', 'If Beale Street Could Talk');
movie.set('rating', 5);
movie.set(1, 'Test to show a number can be used as a key');
get()
- returns a value mapped to a specified key.
console.log(movie.get('name')); //If Beale Street Could Talk
console.log(movie.get('rating')); //5
console.log(movie.get(1)); //Test to show a number can be used as a key
has()
- returns a boolean indicating if a specified key exists or not.
console.log(movie.has('rating')); //true
forEach()
- executes a provided function for each key/value pair.
movie.forEach( (value, key) => console.log(`this ${key} is mapped to ${value}`) );
//name is mapped to "If Beale Street Could Talk"
//rating is mapped to "5"
//1 is mapped to "Test to show a number can be used as a key"
keys()
- returns a new iterator object that contains the key of each element.
for (let key of movie.keys()) {
console.log(key);
}
// name
// rating
// 1
values()
- returns a new iterator object that contains the value of each element.
for (let value of movie.values()) {
console.log(value);
}
// If Beale Street Could Talk
// 5
// Test to show a number can be used as a key
entries()
- returns a new iterator object that contains the [key, value] pairs of each element.
for (let [key, value] of movie.entries()) {
console.log(`${key} » "${value}"`);
}
// name » "If Beale Street Could Talk"
// rating » "5"
// 1 » "Test to show a number can be used as a key"
delete()
- removes specified element(s) from Map object.
console.log(movie.delete('rating')); //true
console.log(movie.has('rating')); //false
clear()
- removes all elements in Map object.
console.log(movie.size) //2
movie.clear();
console.log(movie.size) //0
For more information, reference MDN web docs (by Mozilla).