let
currentTemp
;
// implicit value of undefined
const
targetTemp
=
null
;
// target temp null -- "not yet known"
currentTemp
=
19.5
;
// currentTemp now has value
currentTemp
=
undefined
;
// currentTemp appears as if it had never
// been initialized; not recommended
Objects
Unlike the immutable primitive types, which only ever represent one value, objects
can represent multiple or complex values, and can change over their lifetime. In
essence, an object is a container, and the contents of that container can change over
time (it’s the same object with different contents). Like the primitive types, objects
have a literal syntax: curly braces (
{
and
}
). Because curly braces come in pairs, it
allows us to express an object’s contents. Let’s start with an empty object:
const obj = {};
We can name our object anything we want, and normally you
would use a descriptive name, such as user or shoppingCart. We’re
just learning the mechanics of objects, and our example doesn’t
represent anything specific so we just generically call it obj.
The contents of an object are called properties (or members), and properties consist of
a name (or key) and value. Property names must be strings or symbols, and values can
be any type (including other objects). Let’s add a property
color
to
obj
:
obj.size; // undefined
obj.color; // "yellow"
To use the member access operator, the property name must be a valid identifier. If
you want property names that are not valid identifiers, you have to use the computed
member access operator (you can also use this for valid identifiers):
obj["not an identifier"] = 3;
obj["not an identifier"]; // 3
obj["color"]; // "yellow"
You also use the computed member access operator for symbol properties:
const SIZE = Symbol();
obj[SIZE] = 8;
obj[SIZE]; // 8
At this point,
obj
contains three properties with keys
"color"
(a string that is a valid
identifier),
"not an identifier"
(a string that is not a valid identifier), and
SIZE
(a
symbol).
46 | Chapter 3: Literals, Variables, Constants, and Data Types