Understanding data type of dictionary in JavaScript

Print Friendly, PDF & Email

Dictionary is among the commonly used data structures in modern programming because of its benefits so that there has not been any frankly acceptable alternative. Therefore, in this post I am going to how you how to conceive this data structure in jQuery as well as JavaScript in the most elaborate understanding way.

What is Dictionary data structure?

As its name suggested, Dictionary is a type of data structure in Computer Science which is conceived as a key/value pair collection like Cambridge Dictionary. Each entry in such a collection is a pair of two parts: the first is called key when the second is named value. The key can be a string, a number or other primitive types while the value is anything. It is often used to capture type of data where they are classified into groups under names and having many associated elements or members belonged to the same group name.

Comparing to other programming languages, Dictionary in JavaScript is not defined explicitly and natively in term of data structures. As we know, everything is Object so that it can be used flexibly in some ways we could feel strange and unclear like other statically typed languages such as Java or C#. Therefore, you won’t have so-called Dictionary type so it is actually ease to create a Dictionary object.


To ease conceiving a dictionary, I am giving you an example of defining a dictionary called ukPostCodes in JavaScript trying to encode the post codes corresponding their county across the UK. The key is the county name while the post codes registered with that county play as the values.

var postCodes = {
  "City of London": ["E1", "EC1A", "EC1N", "EC1M", "EC1Y"],
  "Cambridgeshire": ["CB1", "CB2", "CB21", "CB22", "SG8"]

Now, we try to extend the example above in a more sophisticated approach. Each entry in the dictionary is a combination of the county name as the entry key while the abbreviation, post codes and remarks are values. Let’s have a look at a bit complicated example below.

var ukPostCodes = {
  "Bedfordshire": ["Beds", codes: ["LU1", "LU4" , "MK17"], ""],
  "Cambridgeshire": ["Cambs", codes: ["CB1", "CB2", "CB3"], ""],
  "City of London": ["C of Lon", codes: ["E1", "EC1A", "EC1N"], ""]


The introductory application brings to you step and step to create, update, add and retrieve elements from or to a dictionary in JavaScript.

Create a dictionary object

// using Object constructor
var dict = new Object();

// or the shorthand way called literal
var dict = {};

You can also initialise a Dictionary with key/value pairs when declaring it if you are using the shorthand direction like we can do with Array in JavaScript.

var ukPostCodes = {
   "Bedfordshire": {abbrev: "Beds", codes: ["LU1", "LU4", "MK17"], remarks: ""},
   "Cambridgeshire": {abbrev: "Cambs", codes: ["CB1", "CB2", "CB3"], remarks: ""},
   "City of London": {abbrev: "C of Lon", codes: ["E1", "EC1A", "EC1N"], remarks: ""}

I have learned a less restricted way to declare and initialise a dictionary from this discussion or that discussion. It isn’t different too much from we have discussed earlier. The only different place is the value is an array instead of another dictionary in the main example.

var states_dictionary= { 
   "CT": ["alex","harry"], 
   "AK": ["liza","alex"], 
   "TX": ["fred", "harry"]

Iterate Key/Value Pairs

A simple JavaScript “for” loop can be used to iterate through your new dictionary.

for(var key in ukPostCodes) {
    var value = ukPostCodes[key];
   // do something with "key" and "value" variables

Applied for the dictionary defined above, we got the list below

Access Key/Value Pairs Directly

The Key/Value pairs can be accessed directly on the dictionary Object either through the indexer or as if it’s directly a property on the object.

// using indexer
var name = ukPostCodes["abbrev"];

// as property
var name = ukPostCodes.abbrev;

Update dictionary

Accessing elements via their index or property is the only way to update content of these elements. For example, below is to change the abbrev of ‘City of London’ to ‘C of London’.

function updateCofLondon() {     
   ukPostCodes["City of London"]["abbrev"] = "C of London";

Add a new element to an existing dictionary

Here shows you how to add new county into the dictionary.

ukPostCodes["Buckinghamshire"] = {name: "Bucks", 
              codes: ["HP10", "UB9", "WD3"], remarks: ""};

Functions can be Key or Value Too!

Since JavaScript is a functional language, functions are objects too. As a result, Functions can also be used as either Key and/or Value on your dictionary. For the Dictionary Key, this really does make sense since the Dictionary is really just an Object which can have functions/methods on it. However using Functions as the value may not be the most obvious for developers most comfortable with non-functional programming languages. Here are some examples of using a Function in both Key and Value of a Dictionary:

var dict = {};

 var f = function() {
    // do something

 // setup Function as Value
 dict['method'] = f;

 // setup Function as Key
 dict[f] = 'some value';

 // execute Function from Value

var method = dict.method;

// get value for Key
var val = dict[f];

Source code

If you are interested in my article, feel free to take a look at my publicly available source code presented in this writing at here.

Hopefully this offers some additional tips/tricks and/or insights into how to work with a kind of dictionary in JavaScript, and how to make it fit into your need. Happy coding!

All constructive comments are welcomed. If you are willing to contribute financial support for our website, please follow the instructions below.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.