How to Populate a Hash Table in JavaScript?

Estimated read time 1 min read

In JavaScript, you can use an object to create a simple hash table. Here are a few ways to populate a hash table:

  1. Create an empty object and add key-value pairs using the object literal syntax:
let myHashTable = {};
myHashTable["key1"] = "value1";
myHashTable["key2"] = "value2";
  1. Use the Object.assign() method to add multiple key-value pairs to an existing object:
let myHashTable = {};
Object.assign(myHashTable, {"key1": "value1", "key2": "value2"});
  1. Use a loop to add key-value pairs to the object:
let myHashTable = {};
for (let i = 0; i < 5; i++) {
  myHashTable["key" + i] = "value" + i;
}
  1. You can also use the Map object to create a more sophisticated hash table. Here’s an example:
let myHashTable = new Map();
myHashTable.set("key1", "value1");
myHashTable.set("key2", "value2");

The Map object allows you to use any data type as the key, not just strings like with the object method.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply