2013 car

JavaScript’s Map Object

Often lookup tables/hash maps are implemented as objects in JavaScript. But the Map object is better since it is more specialized:

  • Maps are not inherited from Object, so there are no default keys to accidentally override.
  • It has a size property. Objects keys must be manually counted to get the size.
  • The map key can be any value including an object (object keys auto-convert to strings)

Comparisons are done using ===, so using non-primitive values is not very useful since the original object would have to be used. Though not converting every key to a string does have advantages. For example, this simulates adding to a map over time which a sort by date:

// Rough launch dates in MM/DD/YYYY
const cars = new Map();
cars.set(new Date('09/01/2013'), '4C');
cars.set(new Date('07/04/1989'), 'miata');
cars.set(new Date('09/01/1996'), 'elise');

console.log(cars.size);
// 3

// later in the code
const byDate = [];
cars.forEach(function(value, key) {
  const result = { name: value, date: key };
  if (byDate.length === 0 || key <= byDate[byDate.length - 1].date) {
    byDate.push(result);
  } else {
    byDate.splice(byDate.length - 1, 0, result);
  }
});

console.info(byDate);
// [ { name: '4C', date: 2013-09-01T04:00:00.000Z },
//   { name: 'elise', date: 1996-09-01T04:00:00.000Z },
//   { name: 'miata', date: 1989-07-04T04:00:00.000Z } ]

Notice how a normal forEach loop can be added. The loop is also gauranteed to happen in order of insertion while object property iteration order varies per environment. Doing this with an object based hash map would require a strategy like saving each data as a string of its timestamp (making the keys less readable). Then extracting and converting them which is a cumbersome process.