My Development Notes

Programming Made Easier


Maps in JavaScript : Fundamentals with Practicals

The Map is a data structure that maps values to keys. Data is stored inside a key value pair in Map. However, Maps and Objects are different. In objects, keys are generally strings(or symbols) but in Maps there can be any type of keys (objects, strings, arrays or even other maps).

To create a new map use new Map() method:

const basketOrganic = new Map([
  ["Potatoes", 33],
  ["Cucumber", 4],
  ["Bananas", 50],
  ["Apples", 88],
  ["Gourd", 6],
]);

console.log(basketOrganic);
// maps through all the 5 entries

To add elements to map use set() method:

basketOrganic.set('Tomatoes', 12);
// adds sixth item to the map
// {'Potatoes' => 33, 'Cucumber' => 4, 'Bananas' => 50, 'Apples' => 88, 'Gourd' => 6, 'Tomatoes' => 12}

To get the value of a key from a Map we use the get() method:

basketOrganic.get('Cucumber');
// returns 4

To check whether a map contains a certain key use has() method:

basketOrganic.has('Cucumber');
// returns true

basketOrganic.has('Onion');
// returns false

To delete elements from the map use delete() method :

basketOrganic.delete('Apples');
// deletes 'Apples' from the map
// console log to see that's it's gone

To return the number of elements in a map use size property:

basketOrganic.size;
// returns 5 (the total items remaining)

To remove all items inside a map use clear() method :

basketOrganic.clear();
// clears all items inside map
// console log to see if it's cleared 

Examples of Maps in practice :

const cricketMatch = new Map([
  ["1st Over", "8 Runs added"],
  ["2nd Over", "4 Sixers"],
  ["3rd Over", "2 Wide Balls"],
  ["4th Over", "Run Out"],
  ["5th Over", "23 Runs added"],
  ["6th Over", "3 Runs"],
  ["7th Over", "2 Wickets Down"],
  ["8th Over", "17 Runs added"],
]);

for (const [Overs, Happenings] of cricketMatch) {
  console.log(`${Overs}: ${Happenings}`);
}

// returns the below results:
// 1st Over: 8 Runs added
// 2nd Over: 4 Sixers
// 3rd Over: 2 Wide Balls
// 4th Over: Run Out
// 5th Over: 23 Runs added
// 6th Over: 3 Runs
// 7th Over: 2 Wickets Down
// 8th Over: 17 Runs added

Posted

in

by

Tags:

Leave a Reply