Comment
Author: Admin | 2025-04-28
Hash Tables are a data structure that allow you to create a list of paired values. You can then retrieve a certain value by using the key for that value, which you put into the table beforehand.A Hash Table transforms a key into an integer index using a hash function, and the index will decide where to store the key/value pair in memory:_Hash table for storing phone books (from Wikipedia)_You'll commonly use a Hash Table because of its fast search, insertion, and delete operations:Hash Table time complexity in Big O NotationAlgorithmAverageWorst caseSpaceO(n)O(n)SearchO(1)O(n)InsertO(1)O(n)DeleteO(1)O(n)Source from WikipediaThis tutorial will help you understand Hash Table implementation in JavaScript as well as how you can build your own Hash Table class. First, let's look at JavaScript's Object and Map classes.How to Use Hash Tables with Object and Map Classes in JavaScriptThe 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 Nathan is paired with the phone number value of "555-0182" and the key Jane is paired with the value "315-0322":let obj = { Nathan: "555-0182", Jane: "315-0322"}But JavaScript's Object type is a special kind of Hash Table implementation for two reasons: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.For example, the Object prototype has the hasOwnProperty() method which allows you to check if a property is not inherited:const obj = {};obj.name = "Nathan";console.log(obj.hasOwnProperty("name")); // trueJavaScript doesn't block an attempt to overwrite the hasOwnProperty() method, which may cause an error like this:const obj = {};obj.name = "Nathan";obj.hasOwnProperty = true;console.log(obj.hasOwnProperty("name")); // Error: obj.hasOwnProperty is not a functionTo handle these shortcomings, JavaScript created another implementation of the Hash Table data structure which is called MapJust 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("Nathan", "555-0182");collection.set("Jane", "555-0182");console.log(collection.get("Nathan")); // 555-0182console.log(collection.size); // 2Unlike 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
Add Comment