Hash
Learn what hash is and how it works.
We'll cover the following
What is a hash?
Hash data structure has many names: hash, hash table, map, dictionary, and even object in JavaScript. Hash and array are essential data structures for any programmer. These data structures are different, but they were designed for the same goal: to store and retrieve data. The only difference is how these two operations are implemented.
What is an array, and how do we store and get the data back from an array? Imagine that a child has lots of toys. The mother puts all these toys on a single shelf and assigned a sequential number to each: one, two, three and so on. We need to visually scan the entire shelf if we want to find our favorite toy. It can take some time if the shelf is long enough. However, we can easily find a toy if we know its number.
Hash looks like a magic bucket. There is no order, and we don’t know how it works. We can put any object to this magic bucket and assign a name: “Hey, magic bucket, here is a ball.” We can also get any object from it: “Hey, magic bucket, give me this thing called a ball.” The important detail is that we name things and use this name to get objects back. This name is the key (or hash key). Item lookup happens in constant time, immediately.
Working
But how does this magic bucket work? Why, in the case of the array, do we have to scan the entire shelf while the magic bucket takes no time? The secret is its inner organization and how it works under the hood: there are multiple small buckets—“bucket” is the actual name for inner structure—and the object goes to the specific small bucket, depending on its characteristics, such as color. More objects require more inner buckets to be present.
If the hashes are so good, why not always use them?
First, this data structure does not guarantee any order. If we add data to an array using push
, we know exactly which element was added first and which one was added later. But there is no order in the hash once the value is there, so there is no way to tell when it got there.
Note: Although the hash data structure doesn’t guarantee any order, the order is guaranteed by Ruby hash implementation, but we wouldn’t recommend relying on it. Theofficial documentation says:
“Hashes enumerate their values in the order that the corresponding keys were inserted.”
But since any web developer should know JavaScript at least at a minimum level, let’s see what the documentation on JavaScript says about it:
“An object is a member of the type Object. It is an unordered collection of properties containing a primitive value, object, or function.”
However, in the newer version of JavaScript (ES6 and above), the Map
class, one of the hash implementations, will return values from the hash in order. So the general rule here is not to rely on the hash order.
Get hands-on with 1400+ tech skills courses.