TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVASCRIPT

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.

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

Part B: We access the "cat" field on the object twice. This key exists, so we get a value each time.

Part C: Here we access a key that does not exist. The value returned is undefined—this is a special value.

JavaScript program that uses object, properties // Part A: create dictionary. var lookup = {"cat": 400, "dog": 600}; // Part B: get the value for the cat string. console.log("LOOKUP SYNTAX 1: " + lookup.cat); console.log("LOOKUP SYNTAX 2: " + lookup["cat"]); // Part C: 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: ecma-international.org

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
Benchmark, properties. Modern JavaScript compilers optimize the lookup of properties on objects. Should we access properties without quotes, and treat them more like fields?

Version 1: This version of the code accesses a property like a field—it does not pass a string argument.

Version 2: Here we access the "fish" property by using the string "fish." This is more like dictionary-style syntax.

Result: Currently in 2019, Chromium seems to execute direct property accesses faster than string keys on objects.

JavaScript program that benchmarks property access var lookup = {"bird": 100, "frog": 200, "fish": 300}; var y = 0; var x1 = performance.now(); // Version 1: access property directly. for (var i = 0; i < 10000000; i++) { y += lookup.fish; } var x2 = performance.now(); // Version 2: access property by string name. for (var i = 0; i < 10000000; i++) { y += lookup["fish"]; } var x3 = performance.now(); // Results. console.log("TIME 1: " + (x2 - x1)); console.log("TIME 2: " + (x3 - x2)); Output TIME 1 (2019): 77.000 TIME 2: 91.834
Benchmark, array. Here is an interesting benchmark in Chromium. We consider using objects with integer properties instead of arrays.

Version 1: In this version of the code, we see logic that assigns 100 integer properties to an object.

Version 2: Here we assign 100 elements in an array. So we use an array instead of an object.

Result: Currently in 2019 it is faster to assign into an array repeatedly than use integer object properties in Chromium.

JavaScript program that benchmarks object integer properties var lookupArray = []; var lookupObject = {}; var x1 = performance.now(); // Version 1: add 100 properties to an object based on integers. for (var i = 0; i < 100000; i++) { for (var v = 0; v < 100; v++) { lookupObject[v] = i; } } var x2 = performance.now(); // Version 2: assign 100 elements to an array. for (var i = 0; i < 100000; i++) { for (var v = 0; v < 100; v++) { lookupArray[v] = i; } } var x3 = performance.now(); // Results. console.log("TIME 1: " + (x2 - x1)); console.log("TIME 2: " + (x3 - x2)); Output TIME 1 (2019): 87.209 TIME 2: 22.880
Benchmark, Object.keys. 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.

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

Version 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 benchmarks Object.keys var dictionary = {"cat": 1, "bird": 2, "frog": 500}; var x1 = performance.now(); // Version 1: benchmark Object.keys. for (var i = 0; i < 1000000; i++) { var result = Object.keys(dictionary); if (result.length != 3) { break; } } var x2 = performance.now(); // Version 2: use a cached copy of Object.keys. for (var i = 0; i < 1000000; i++) { if (result.length != 3) { break; } } var x3 = performance.now(); // Results. console.log("TIME 1: " + (x2 - x1)); console.log("TIME 2: " + (x3 - x2)); Output TIME 1 (2019): 22.359 TIME 2: 3.190
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 Returns
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. Objects are versatile and can be though of as dictionaries.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf