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"
}
- It has properties added by the Object class. Keys you input may conflict and overwrite default properties inherited from the class.
- 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.
- const obj = {};
- obj.name = "John";
- console.log(obj.hasOwnProperty("name")); // true
- const obj = {};
- obj.name = "John";
- obj.hasOwnProperty = true;
-
console.log(obj.hasOwnProperty("name"));
// Error: obj.hasOwnProperty is not a function
Just like Object, Map allows you to store key-value pairs inside the data structure. Here's an example of Map in action:
- const collection = new Map();
- collection.set("John", "555-1234");
- collection.set("Jane, "555-9876");
-
console.log(collection.get("John")); // 555-1234
console.log(collection.size); // 2
You also can't overwrite Map inherited properties. For example, the following code tried to overwrite the size property value to false:
- const collection = new Map();
- collection.set("John", "555-1234");
- collection["size"] = false;
-
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.
- const myMap = new Map();
- myMap.set("John", "555-1234");
- myMap.set("Jane", "555-9876");
- for (let [key, value] of myMap) {
console.log(`${key} = ${value}`);
}