If you’re following along in a JavaScript console, you may notice
that the console doesn’t list the SIZE symbol as a property of obj. It
is (you can verify this by typing obj[SIZE]), but symbol properties
are handled differently and are not displayed by default. Also note
that the key for this property is the symbol SIZE, not the string
"SIZE"
. You can verify this by typing obj.SIZE = 0 (the member
access property always operates on string properties) and then
obj[SIZE]
and obj.SIZE (or obj["SIZE"]).
At this juncture, let’s pause and remind ourselves of the differences between primi‐
tives and objects. Throughout this section, we have been manipulating and modifying
the object contained by the variable
obj
, but
obj
has been pointing to the same object
all along. If
obj
had instead contained a string or a number or any other primitive, it
would be a different primitive value every time we change it. In other words,
obj
has
pointed to the same object all along, but the object itself has changed.
In the instance of
obj
, we created an empty object, but the object literal syntax also
allows us to create an object that has properties right out of the gate. Inside the curly
braces, properties are separated by commas, and the name and value are separated by
a colon:
const
sam1
=
{
name
:
'Sam'
,
age
:
4
,
};
const
sam2
=
{
name
:
'Sam'
,
age
:
4
};
// declaration on one line
const
sam3
=
{
name
:
'Sam'
,
classification
:
{
// property values can
kingdom
:
'Anamalia'
,
// be objects themselves
phylum
:
'Chordata'
,
class
:
'Mamalia'
,
order
:
'Carnivoria'
,
family
:
'Felidae'
,
subfaimily
:
'Felinae'
,
genus
:
'Felis'
,
species
:
'catus'
,
},
};
In this example, we’ve created three new objects that demonstrate the object literal
syntax. Note that the properties contained by
sam1
and
sam2
are the same; however,
they are two distinct objects (again, contrast to primitives: two variables that both con‐
tain the number 3 refer to the same primitive). In
sam3
, property
classification
is
itself an object. Consider the different ways we can access Sam the cat’s family (it also
doesn’t matter if we use single or double quotes or even backticks):
Objects | 47