We will start with simple object literals.
Most typically objects are parts of classes and instantiated by calling the class constructor. We will discuss these objects shortly. For now we will learn some basic methods for working with objects, by looking at “objects as dictionaries”.
Object literals are enclosed in curly braces:
let a = {
foo: 123,
"bar": "hello",
"properties can be any string": "values can be anything",
even: { other: "objects" }
};
a["foo"]
a.foo
You can also access a property if you have it as a variable value:
let b = "foo";
a[b]; // same as a["foo"]
a["foo"] = 3
, a.foo = 3
.delete a.foo
.a.even.other
.hasOwnProperty
to determine if an object has a specific property: a.hasOwnProperty("bar")
Two special values of importance: null
, undefined
. Both tend to indicate the absence of a value. The difference is that the former of those is an object:
typeof null;
typeof undefined;
undefined
. This is very different behavior than in Python.You can also set the value of a property to equal undefined
. This is different from not having that property:
let a = { foo: 5 };
a.bar = undefined;
a.hasOwnProperty("bar"); // returns true
Here are some key tasks with dictionaries and how to carry them out:
let o = { key1: val1, key2: val2, ... };
o[keyString] = newValue;
o.key = newValue;
o[keyString];
o.key;
o.hasOwnProperty(keyString);
// Approach 1
for (let key in o) {
if (o.hasOwnProperty(key)) { // <--- Must do this check!
let value = o[key]; // Declaration should be earlier
// Do things with key, value
}
}
// Approach 2
let keys = Object.keys(o); // <-- Returns array of keys
for (let i = 0; i < keys.length; i += 1) {
let key = keys[i]; // Declaration should be earlier
let value = o[key]; // Declaration should be earlier
// Do things with key, value
}