An overview of Javascript fundementals
Map is a data structure in JavaScript which allows storing of [key, value] pairs where any value can be either used as a key or value.
The keys and values in the map collection may be of any type and if a value is added to the map collection using a key which already exists in the collection,
then the new value replaces the old value. When we iterate over the map object it returns the key,value pair in the same order as inserted.
We use new Map()
to instantiate a new map object.
let teachers = new Map(); teachers.set("grade 1", "Mrs Johnson"); teachers.set("grade 2", "Mr Bennett"); for (let [key, value] of teachers) { console.log(key + ' = ' + value); } //output: // grade 1 = Mrs Johnson // grade 2 = Mr Bennett for (let key of teachers.keys()) { console.log(key); } //output: // grade 1 // grade 2 for (let key of teachers.values()) { console.log(value); } //output: // Mrs Johnson // Mr Bennett for (let [key, value] of teachers.entries()) { console.log(`The ${key} teacher is ${value}.`); } //output: // The grade 1 teacher is Mrs Johnson // The grade 2 teacher is Mr Bennett
Here are some map methods:
let fruitColors = new ; .set(, ); fruitColors.(, ); .set(, "red"); try Again!