C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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
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
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
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.orgWarning: 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
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
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
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
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
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
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
And: Features like constructors and methods are optional. A class in its simplest form is a dictionary (or hash, or map).
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).