Hash Table - Javascript

Hash Tables (use Map data structure in JS)

key/value pairs

we can getaway with object literal though

use hash tables more in other prg languages

The most common example of a Hash Table in JavaScript is the Object data type, where you can pair the object's property value with a property key.

In the following example, the key John is paired with the phone number value of "555-1234" and the key Jane is paired with the value "555-9876":

let obj = {

John: "555-1234",

Jane: "555-9876"

}

But JavaScript's Object type is a special kind of Hash Table implementation for two reasons:
  1. It has properties added by the Object class. Keys you input may conflict and overwrite default properties inherited from the class.
  2. The size of the Hash Table is not tracked. You need to manually count how many properties are defined by the programmer instead of inherited from the prototype.
For example, the Object prototype has the hasOwnProperty() method which allows you to check if a property is not inherited:
  1. const obj = {};
  2. obj.name = "John";
  3. console.log(obj.hasOwnProperty("name")); // true
JavaScript doesn't block an attempt to overwrite the hasOwnProperty() method, which may cause an error like this:
  1. const obj = {};
  2. obj.name = "John";
  3. obj.hasOwnProperty = true;
  4. console.log(obj.hasOwnProperty("name"));

    // Error: obj.hasOwnProperty is not a function

To handle these shortcomings, JavaScript created another implementation of the Hash Table data structure which is called Map

Just like Object, Map allows you to store key-value pairs inside the data structure. Here's an example of Map in action:

  1. const collection = new Map();
  2. collection.set("John", "555-1234");
  3. collection.set("Jane, "555-9876");
  4. console.log(collection.get("John")); // 555-1234

    console.log(collection.size); // 2

Unlike the Object type, Map requires you to use the set() and get() methods to define and retrieve any key-pair values that you want to be added to the data structure.

You also can't overwrite Map inherited properties. For example, the following code tried to overwrite the size property value to false:

  1. const collection = new Map();
  2. collection.set("John", "555-1234");
  3. collection["size"] = false;
  4. console.log(collection.get("size")); // undefined

    console.log(collection.size); // 1

    As you can see from the code above, you can't add a new entry to the Map object without using the set() method.

The Map data structure is also iterable, which means you can loop over the data as follows:
  1. const myMap = new Map();
  2. myMap.set("John", "555-1234");
  3. myMap.set("Jane", "555-9876");
  4. for (let [key, value] of myMap) {

    console.log(`${key} = ${value}`);

    }