Sets and Maps in ECMAScript 5

In ECMAScript 5, developers mimicked sets and maps by using object properties, like this:

  1. let set = Object.create(null);
  2. set.foo = true;
  3. // checking for existence
  4. if (set.foo) {
  5. // do something
  6. }

The set variable in this example is an object with a null prototype, ensuring that there are no inherited properties on the object. Using object properties as unique values to be checked is a common approach in ECMAScript 5. When a property is added to the set object, it is set to true so conditional statements (such as the if statement in this example) can easily check whether the value is present.

The only real difference between an object used as a set and an object used as a map is the value being stored. For instance, this example uses an object as a map:

  1. let map = Object.create(null);
  2. map.foo = "bar";
  3. // retrieving a value
  4. let value = map.foo;
  5. console.log(value); // "bar"

This code stores a string value "bar" under the key foo. Unlike sets, maps are mostly used to retrieve information, rather than just checking for the key’s existence.