How to use javascript hashes (or hash-table)

Javascript has no hash table object. In fact, all objects are hashes.

  1. var hashPetName = new Object();
  2. hashPetName["dog"] = "Rex";
  3. hashPetName["cat"] = "Mistigri";
  4.  
  5. console.log("My dog’s name is " + hashPetName["dog"]
  6.         + " and my cat’s name is " + hashPetName["cat"] );
  7.  

It’s a little overwhelming to write it like that so let’s use a simpler form.

  1. var hashPetName = {
  2.   dog: "Rex",
  3.   cat: "Mistigri"
  4. }
  5.  
  6. console.log("My dog’s name is " + hashPetName["dog"]
  7.         + " and my cat’s name is " + hashPetName["cat"] );
  8.  

Great! That’s it about javascript hashes, now I can go groom my cat.

Wait!!!

Why can I use an object to emulate a hash? Can I do the same thing with a Number object? Let’s try with the same code than above but with a Number instead of an Object.

[source:javascript]
var hashPetName = new Number(); // Magic is here!
hashPetName["dog"] = “Rex”;
hashPetName["cat"] = “Mistigri”;

alert(“My dog’s name is ” + hashPetName["dog"]
+ ” and my cat’s name is ” + hashPetName["cat"] );
[/source]

It works!!! What can we understand of this?

All objects are hashes too

When you are javascripting, forget everything you know about other languages, it won’t be any help.

I’m adding to the list

  • All objects are hashes

When we create an object, its properties and methods are added to the hash of the object.

[source:javascript]
// Create a class
function TheClass() {
// Adding a property
this.name = “the name”;
}

// Create the object
theObject = new TheClass();

// Alert the property name
alert(theObject.name);

// Alert the property name using the hash
alert(theObject["name"]);
[/source]

In this example, you see that using theObject.theProperty is the same thing that using theObject["theProperty"].

Dynamically add a property/method to the object

In my first example, I didn’t create the property in the constructor before using it. As you saw, it’s easy to dynamically add a property or a method.

[source:javascript]
// Create a class
function TheClass() {
}

var theObject = new TheClass();

theObject["age"] = 3; // Create a new ‘age’ property
theObject.fullName = “Mistigri”; // Create a new ‘fullName’ property

theObject.alertDetail = function() {
alert(this["fullName"] + ” is ” + this.age);
}

theObject["alertDetail"]();
[/source]

Beware! The new property/method will only be available to the instance you’re working on. If you want to add a new property/method to every instances of the class, use prototypes.

Using an array thinking it’s a hash

One of the most common mistake I see is to use an Array object thinking that’s the only one that you can use the brackets to create a hash. Even if it works, it’s not how it should be done. I recommend the use of Object instead.

[Update : A friend of mine pointed me out that I should have talked about hash tables (or associative arrays) instead of hashes.]

  • http://www.weaselhat.com Michael Greenberg

    Objects make terrible hashes in JavaScript, though, since the only valid key types are Number and String. They’re addressing this in ES4, but for now there’s no general hashtable for JavaScript.

  • Dan

    Michael, how can we do hash table less terrible?

  • http://www.weaselhat.com Michael Greenberg

    Well, without a notion of (semi-)unique object id, there’s not much to be done. If you look at the ES4 discussion list, you’ll see that they’ve come up with intrinsic::hashcode, which computes a non-unique object id. You could implement a bucket hash table with that, but they don’t provide one out of the box.

    The mailing list is open and (from what I’m told) pretty receptive. So if you need hash tables for something, by all means mention it.

  • Dan

    Thanks! I subscribed to the mailing list.

  • Manuel

    “Only valid key types are number and String”.

    That is very ok for me!

    Thanks Dan.

  • Thomas

    Hi Dan,

    thanks a lot.
    It really helpt me to understand how objects work in JS.

    And: “Only valid key types are number and String”.
    That’s also fine with me

    Cheers, Thomas

  • John

    Hello dude, Thanks a lot for this post. I really need this one in my project. Thank you once again……

  • http://igrkio.info web developer

    this is not a best way to create hash in javascript

    #var hashPetName = new Object();
    #hashPetName["dog"] = “Rex”;
    #hashPetName["cat"] = “Mistigri”;

    use this instead
    var hashPetName={dog:’rex’,cat:’Mistigri’};

  • http://www.bilderfarm.de/ Nightfly

    Using objects as associative arrays have severe shortcomings in JS.
    It’s ok and fast to use them when you just want to index into a set of data with a non-numeric key (string), but if you use libraries such as Prototype you can’t iterate over the keys because those libraries add stuff to Object()’s prototype, making them properties of any objects you create and thus polluting your hash tables.
    You can use Prototype’s (to stay with that lib) Hash object (http://prototypejs.org/api/hash) to work around this, but it’s very slow compared to native objects.

  • http://wiki.dandascalescu.com Dan Dascalescu

    @nightfly: you can filter out properties inherited through the prototype chain using the hasOwnProperty Object method.

  • http://nehagiri.blogspot.com Nehagiri

    very cooool! :-)

  • Bigjeff5

    Just an FYI, the name of the website is absent from the links in this post (which means they go nowhere).

  • Mike

    That's fine if you already know what you are adding, but it would seem to me to be a little kludgy using that format when dynamically adding values to a hash table, which is the most typical use case.

  • http://www.javascriptkata.com dsimard

    You could do this :

    var hashPetName={dog:'rex',cat:'Mistigri'};
    hashPetName["ferret"] = 'Rocky';

  • http://www.jlabstudio.com/webgl/2011/11/webgl-tutorial-6-eventos-de-teclado-y-filtros-de-textura/ WebGL Tutorial 6 – Eventos de teclado y filtros de textura · Experimentando en la web

    [...] Bright Hub fue una buena ayuda sobre consejos de uso de los eventos de teclado, y este artículo de Javascript de Kata me ilustró sobre la utilización de diccionarios. Y como siempre, estoy profundamente agradecido a [...]