JavaScript Basics Tutorial

An overview of Javascript fundementals

Maps

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.

Example


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


            

Map methods can be used to manipulate, set or access data stored in a map object

Here are some map methods:

  • has() - checks to see if a key exists in the map and returns a boolean
  • get() - returns the value of the given key
  • delete() - deletes the given key-value pair from the map
  • clear() - removes all key-value pairs in a map
  • entries() - returns the [key, value] pairs of all the elements of a map in the order of their insertion

Exercise

  1. Create a new map object called fruitColors
  2. Set the following fruit names as keys in their order: banana, naartjie, apple.
  3. Set the following values as their colors, respectively: yellow, orange, red.

let fruitColors = new ;

.set(, );
fruitColors.(, );
.set(, "red");

  try Again!
            
 prev  Arrays and Loops
Functions  next