How to write a HashTable Class in JavaScript

Sometimes it's good to study in order to learn how something works. Other times, it's better to just build the thing and learn what needs to be done in order to make it work.

So in this article, we’ll go through a HashTable Class written in Javascript.

If you’d like to learn more about HashTables, check out my blog here that goes into them.

But for those of you who have read that post (or don’t need to) let's get straight to it.

Hash Maps, Maps, Dictionaries, Objects, they’re all different ways of describing a hashTable. There may be differences between them depending on the language, but generally speaking, the fundamental principle behind them is that they are key-value-paired. Meaning that every value stored within a hashTable will have a corresponding unique key that allows for the value to be found very quickly.

So here are the requirements for the class:

  • must be able to declare the size of the HashTable upon creation
  • each value needs a unique/hashed identifier → needs a key
  • must be able to set values to keys
  • must be able to get value when the key is called
  • must be able to see all keys returned as an array

Now…. GO! Try and build this HashTable Class — I’ll wait for you here.

How’d it go?

Let’s compare it to my version.

See if you can decipher what’s happening.

Did you get an idea of how things are working? How’d it compare to your version?

Let’s see it with some comments this time around.

Now if you didn’t try and write up this class… I HIGHLY RECOMMEND YOU DO!
Go on and try to build it yourself from memory! It will seriously up your understanding of how the whole thing works.

And that's all for this one folks.

Happy Hacking!

Just another one of those dreamers with a sparkle in his eyes.