Javascript Map

Knowing and understanding #javascript data structures in programming is essential. One of those very useful data structures in javascript is a Map. A map holds key-value pairs and remembers the insertion order of those keys. There are a number of methods available on the map data structure that can make your life as a web developer much easier.

Let’s see some quick example usages of Map to see why it can be very useful.

// pass an iterable object to the Map constructor
const writingUtensils = new Map([
    [pen, 'blue'],
    [marker, 'green'],
    [chalk, 'white']
]);

// use a key to obtain the value
writingUtensils.get(marker) // 'green'

// check if we have a particular key
writingUtensils.has(pencil) // false

// number of elements in map
writingUtensils.size // 3

// iterate over a map - for keys or values
for (const utensilName of writingUtensils.keys()) {
  console.log(utensilName)
  // pen
  // marker
  // chalk
}

for (const utensilColor of writingUtensils.values()) {
  console.log(utensilColor)
  // blue
  // green
  // white
}

Read more about it here

Instagram Post