Maps are a new data strucure in es6 designed to store key / value pairs.
Maps are designed to replace object literals for storing key/value pairs.
Using the new map data structure is beneficial because it gives us access to some handy properties.
These properties allow us to iterate over maps, use any data type as keys and easily add or remove data.
We can use object literals to store key/value pairs. For example:
var oldCar = {
"make": "Toyota",
"model": "Corolla",
"year": 1999
}
console.log(oldCar.year) // retrieve the value of the year of the oldCar.
Create a new instance of a Map. Use the `set` keyword to set the key value pairs and the `get` keyword to retrieve values. For example:
// the new way
let newCar = new Map(); // create a new instance of Map.
// set the key / value pairs
newCar.set('make','Toyota');
newCar.set('model','Tacoma');
newCar.set('year',2018);
console.log(newCar.get('year')); // retrieve the value of the year of the newCar.
Determine the number of unique keys in the Map
console.log(newCar.size); // checks size of the map. Expected output: 3;
newCar.set('year',2019);
console.log(newCar.size); // expected output still 3. We just overwrote the value for the key `year`
The delete property of maps lets you remove a key from the map.
// use the `delete` method to remove coffee in the shopping cart
newCar.delete('make');
The `has` property of sets lets you check if items are in the set.
// use the `has` method to check if these keys exist in the newCar map.
console.log(newCar.has('year')); // true
console.log(newCar.has('brakes')); // false