Working With JavaScript Hashes

Yesterday, I started learning JavaScript, since that is one of the most important languages any web developer needs to know. Coming from a Java and Ruby background, one of the first things I wanted to do in JavaScript was create a Hash. To my surprise I found out that there are no “Hashes” in JavaScript. Instead, JavaScript has Objects (that’s where the JSON format comes from).

I was very lucky to get help from Marcus Phillips, a JavaScript engineer at Twitter. So in case you’re confused about how to work with JavaScript Objects, here are some of the lessons I’d like to share:


I’m going to use creating an english dictionary as an example.

Creating A JavaScript Object

Creating an empty object:

var english = {}

Creating an object with existing key-value pairs:

var english = {
  house: "A building for human habitation",
  tree:"A woody perennial plant",
  street: "A public road in a city or town"
};

As you can see from the above examples, JavaScript objects are very similar to Hashes and Objects in other programing languages.

Adding To JavaScript Objects

Adding an additional key-value pair to our english object, is also similar to other languages.

In this example, I’ll be adding the definition of Hacker to the english dictionary:

english.hacker = "An enthusiastic and skillful computer programmer or user."

Another way to do this, which should only be used if you don’t have the exact value, since the value is generated more dynamically. So for example, let’s say someone enters a word and definition to add to the hash.

english[word] = definition

/* translates to */
english["hacker"] = "An enthusiastic and skillful computer programmer or user."

Prototyping

Now, let’s say we also want to create a British English dictionary, which has the same definitions as the english dictionary and a few more British English – specific words like lift and lorrie:

/* Option 1: Create the British English Object and add in the extra definitions later */

/* britishEnglish inherits all the definitions from english */
var britishEnglish  = Object.create(english); 

/* add in additional britishEnglish only definitions */
britishEnglish.lift ="Raise to a higher position or level";
britishEnglish.lorrie ="A large, heavy motor vehicle for transporting goods or troops";

/* Option 2: Create the British English Object and add in the extra definitions on creation */
var britishEnglish = Object.create(english, {
  lift: "Raise to a higher position or level",
  lorrie: "A large, heavy motor vehicle for transporting goods or troops"
});

Retrieving Values

Now let’s retrieve the definition of a “tree” from the english dictionary:

english.tree

That’s it! JavaScript Objects just seem intimidating, but they’re actually pretty simple and work pretty much the same as Hashes and Objects in other languages.

Enjoy the article? Join over 17,500+ Swift developers and enthusiasts who get my weekly updates.