JavaScript Object, Dictionary Examples

Use objects to provide lookups from keys to values. Objects have properties.
Object. A meteor falls from above. This is an object from outer space. It has effects—it forms a crater on impact. It has parts (minerals).
In JavaScript too we have objects with effects and parts. With functions we add effects to an object. With properties we add parts—ints or strings.
Lookup example. Imagine some animals like a cat and a dog. Each has an associated number like a weight. We can place these animals in an object and get this number.

Note: We use a special literal syntax to declare the dictionary object. Keys and values can be added (or removed) later too.

Undefined: If no key is found, the value returned is undefined. This is a special value in JavaScript.

JavaScript program that uses object, properties var lookup = {"cat": 400, "dog": 600}; // Get the value for the cat string. console.log("LOOKUP SYNTAX 1: " +; console.log("LOOKUP SYNTAX 2: " + lookup["cat"]); // Get a nonexistent value. console.log("NONEXISTENT: " + lookup["?"]); Output LOOKUP SYNTAX 1: 400 LOOKUP SYNTAX 2: 400 NONEXISTENT: undefined
Quotes. Object literal syntax does not require quotes for keys. We can use string or number keys with no quotes. This reduces the size of JavaScript files.

Tip: JavaScript files must be parsed before they are executed. Fewer characters can make them faster to parse.

JavaScript program that uses object, no key quotes // Quotes are not needed in object literal keys. var colors = {yellow: "#FFFF00", silver: "#C0C0C0"}; console.log("VALUE: " + colors.yellow); console.log("VALUE: " + colors["silver"]); Output VALUE: #FFFF00 VALUE: #C0C0C0
Function. With objects we can place a function in the value part for a key. So when the associated key is used, it can be called like a function.

Here: The box object has a width and height. We specify a function() for the "area" key and call it directly.

JavaScript program that uses object with function // Create a box object. // ... Set its width, height, and use a function for area. var box = { width: 2, height: 3, area: function() { return this.width * this.height; } }; // Write object properties. console.log("WIDTH: " + box.width); console.log("HEIGHT: " + box.height); console.log("AREA: " + box.area()); Output WIDTH: 2 HEIGHT: 3 AREA: 6
Object.keys. Consider an object. It has many keys, but we cannot access them in an easy way like we can an array. We must use a method like Object.keys to get an array of the keys.

Warning: This method returns an array. It also is defined by the specification to loop over the entire object. So it may be slow.

JavaScript program that uses Object.keys // Create object with 3 keys. var test = {"js": 1, "python": 0, "perl": -1}; // ... Add one more key. test["ruby"] = 0; // Get keys. var result = Object.keys(test); // ... Write the keys in a loop. for (var i = 0; i < result.length; i++) { console.log("KEY: " + result[i]); } Output KEY: js KEY: python KEY: perl KEY: ruby
Key count. An object has no length property. But it has a certain number of keys. With Object.keys we can get those keys, and then use length on that variable.

Result: This object has three keys added to it. With Object.keys we discover this information.

Quote: For each own enumerable property of O whose name String is P, call the DefineOwnProperty internal method of array with arguments ToString(index).

ECMAScript Language Specification:

Warning: According to the language specification, this method loops over the object's internals. Be careful with performance here.

JavaScript program that gets key count // Example object with 3 keys. var test = {}; test["cat"] = 100; test[200] = "bird"; test["blue"] = ["red", "frog"]; // Use Object.keys to get keys from object. var keys = Object.keys(test); // ... Use length on keys to get key count. console.log("OBJECT KEY COUNT: " + keys.length); Output OBJECT KEY COUNT: 3
In operator. Sometimes we wish to see if a key exists in an object. We can use the "in" keyword to search the keys and return true if a key exists.

Tip: This syntax can be used for feature detection—we can find supported properties on the "window" object, for example.

JavaScript program that uses in keyword on object var data = {bird: 10, frog: 20}; // Use "in" to see if an object contains a key. if ("bird" in data) { console.log("TRUE"); } if ("apple" in data) { console.log("FALSE"); // Not reached. } Output TRUE
Nested object. An object can be part of another object. And that nested object can also have sub-objects. We can construct entire trees of objects in this way.

Here: We create an object that has a sub-object. We then link that object to the original object, creating a circular reference.

Warning: This example helps us see how objects may be linked together, but it is not helpful in many real programs.

JavaScript program that uses object inside object // Create an object. var empty1 = {}; empty1.color = "orange"; // Create an object as part of the previous object. empty1.subobject = {}; empty1.subobject.color = "blue"; // Reference original object. empty1.subobject.subobject2 = empty1; // An object references itself. console.log("SUBOBJECT COLOR: " + empty1.subobject.subobject2.color); Output SUBOBJECT COLOR: orange
Multi-map. Sometimes we want to look up an array from a key. This type of collection is sometimes called a multi-map. One key has multiple values.

Program: We create an empty object with the identifier "test." We then invoke the add() function to add things to the object.

Add: This function sees if an array exists at the requested key. If no array exists, a new, 1-element array is created.

Push: If an array exists already, we push another value to it. So we add an element to an existing array.

JavaScript program that implements multi-map object function add(test, key, value) { if (!test[key]) { // Create 1-element array with this value. test[key] = [value]; } else { // Append element to existing array. test[key].push(value); } } // Create new object. var test = {}; // Add elements to arrays in object. add(test, "cat", 10); add(test, "cat", 20); add(test, "bird", 0); // Get arrays from object. var catItems = test["cat"]; console.log("CAT: " + catItems); var birdItems = test["bird"]; console.log("BIRD: " + birdItems); Output CAT: 10,20 BIRD: 0
Property benchmark. Modern JavaScript compilers optimize the lookup of properties on objects. In this test we compare a direct access (with field syntax) to a string lookup.

Result: In a browser like Chrome the results are about the same. No difference can be seen in multiple runs.

JavaScript program that benchmarks property access var lookup = {"bird": 100, "frog": 200, "fish": 300}; var x1 =; var y = 0; for (var i = 0; i < 1000000; i++) { y +=; } var x2 =; document.title = (x2 - x1) + "/" + y; JavaScript program that benchmarks property string look up var lookup = {"bird": 100, "frog": 200, "fish": 300}; var x1 =; var y = 0; for (var i = 0; i < 1000000; i++) { y += lookup["fish"]; } var x2 =; document.title = (x2 - x1) + "/" + y; Output 54.81 ms direct access 54.79 ms string lookup
Object versus array. Here is an interesting benchmark in Google Chrome. The first program assigns 100 integer properties to an object. The second program assigns 100 elements in an array.

Result: It is faster to use integer properties on an object in Chrome. The compiler optimizes properties better than array elements here.

Thus: For developing optimal JavaScript programs, consider using objects with integer properties instead of arrays.

JavaScript program that assigns object integer properties var x1 =; var lookup = {}; // Add 100 properties to an object based on integers. for (var i = 0; i < 1000000; i++) { for (var v = 0; v < 100; v++) { lookup[v] = i; } } var x2 =; document.title = (x2 - x1) + "/" + lookup[9]; JavaScript program that assigns integer array elements var x1 =; var lookup = []; // Assign 100 elements to an array. for (var i = 0; i < 1000000; i++) { for (var v = 0; v < 100; v++) { lookup[v] = i; } } var x2 =; document.title = (x2 - x1) + "/" + lookup[9]; Output 208 ms object properties [1] 207 ms [2] 208 ms [3] 224 ms array elements [1] 222 ms [2] 224 ms [3]
Object.keys benchmark. Suppose you want the keys to an object. It seems like Object.keys can get these fast, but in this benchmark we see this approach has a cost.

Program 1: This version calls Object.keys on a small object in a tight loop. It checks the length.

Program 2: This version uses just one call to Object.keys and reuses that collection in the loop.

Result: The Object.keys method has a significant cost. It is far faster to cache the result of this method.

JavaScript program that uses Object.keys var dictionary = {"cat": 1, "bird": 2, "frog": 500}; var x1 =; for (var i = 0; i < 1000000; i++) { // Benchmark Object.keys. var result = Object.keys(dictionary); if (result.length != 3) { break; } } var x2 =; document.title = (x2 - x1); JavaScript program that uses cached Object.keys var dictionary = {"cat": 1, "bird": 2, "frog": 500}; var result = Object.keys(dictionary); var x1 =; for (var i = 0; i < 1000000; i++) { // Use a cached copy of Object.keys. if (result.length != 3) { break; } } var x2 =; document.title = (x2 - x1); Output 99.68 ms Object.keys 2.89 ms Object.keys cache
Some notes. In many object-oriented languages, objects are heavier. Objects are instances of classes with constructors. In JavaScript though objects are lighter.

And: Features like constructors and methods are optional. A class in its simplest form is a dictionary (or hash, or map).

Object versus switch. An object can be used to replace a series of if-statements or a switch. In testing, though, a switch appears to execute faster in browsers.function Lookup
Return object. We can return an object literal when we need to return multiple values from a function. The syntax for returning multiple values is clear.Multiple Return Values
V8 compiler. Modern JavaScript engines use advanced object optimizations. In the V8 compiler (part of Chromium) we find property lookups are optimized with hidden classes.

So: No string lookups are needed as properties are accessed. This makes property accesses on objects much faster.

Quote: To reduce the time required to access JavaScript properties, V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes (Design Elements V8).

A review. We can access object properties directly or with a string lookup by name. Browsers optimize both these syntax forms and treat them the same.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls