How to use javascript hashes (or hash-table)

Javascript has no hash table object but you can emulate one by creating a simple object and using brackets.

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

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

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

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.]

Comments

  1. Michael Greenberg April 2, 2007 at 00:11:34

    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.

  2. Dan (maintainer of Javascript Kata) April 2, 2007 at 08:22:51

    Michael, how can we do hash table less terrible?

  3. Michael Greenberg April 2, 2007 at 10:35:34

    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.

  4. Dan (maintainer of Javascript Kata) April 2, 2007 at 12:25:50

    Thanks! I subscribed to the mailing list.

  5. Manuel December 29, 2008 at 14:18:37

    “Only valid key types are number and String”.

    That is very ok for me!

    Thanks Dan.

  6. Thomas January 16, 2009 at 12:31:36

    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

  7. John January 26, 2009 at 14:42:55

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

  8. web developer February 16, 2009 at 09:52:37

    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’};

  9. Nightfly May 22, 2009 at 17:14:01

    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.

Post a comment

Comments are moderated and innapropriate ones won't be approved. Please respect this public space.