JavaScript Maps: A Beginner's Guide

10 Feb 2024
12 minute read
The Map data structure stores key-value pairs and remembers the order in which the keys were inserted. Any value, whether an object or a primitive value, can be used as either a key or a value.

The internal implementation of a Map object in JavaScript varies depending on the JavaScript engine. In general, a Map is typically implemented as a has table or a variant of a hash table, which is a data structure that allows for efficient key-value pair insertion, deletion, and lookup. The Map object is similar to a plain javascript object, but there are some key differences.

The one key difference is that while keys in a Map can be any data type, including objects and primitive values like strings, numbers, and booleans, keys in a plain JavaScript object can only be strings on symbol.

Another significant difference is that Maps preserves the original order in which the keys were inserted, whereas plain object properties do not. Maps also includes several built-in methods for working with data, including has(), set(), get(), forEach(), keys(), values() and entries().

Counting the number word appears in a string

In below example, the Map object is used to count the instances of each word in the string. Using regular expression, we split the string into an array of words. Then, we iterate over the words, adding each word to the Map object and increasing its count if it already exists.

const text = 'The qucik brown fox jumps over the lazy dog'
// split text by white space
const words = text.split(/\s+/)
// initiazlied a Map
const wordCount = new Map()
// iterate the words
for (const word of words) {
  const count = wordCount.has(word) ? wordCount.get(word) : 0
  wordCount.set(word, count + 1)
}
console.log(wordCount);
/**
 * Map { 
 * 'The' => 1, 
 * 'quick' => 1, 
 * 'brown' => 1, 
 * 'fox' => 1, 
 * 'jumps' => 1, 
 * 'over' => 1, 
 * 'the' => 1, 
 * 'lazy' => 1, 
 * 'dog' => 1 
 * }
 * */