Working with Objects
Property access, computed keys, nested data, and reading values that might not be there.
An object is a bag of named values. A show is an object: it has a title, a year, a list of genres, and a rating.
Making an object
An object literal is a pair of braces with key: value pairs inside. A value
can be anything, including another object.
show.title and show.year read real properties. show.titel is a typo, so
it prints undefined.
A wrong property name is not an error. You find out later, when undefined
turns up somewhere else.
Shorthand properties
When a variable already has the name you want for the key, write it once.
show has the two properties you expect. other has a name, not a title,
so the last line prints undefined.
Dot access and bracket access
Dot notation needs a name you can type out when you write the code. Brackets take any expression, so they also work with a key held in a variable.
The first three lines all print the same date. The last one prints undefined,
because show.field looks for a property literally named field.
Computed keys
The same brackets work when you build an object, not only when you read one. Put the expression in brackets on the left of the colon.
[field]: value used the value of field as the key, so show.network works.
In wrong the key really is field, so wrong.network is undefined.
This is how one function can set whichever field a form changed.
Nested objects
Real show data nests. You walk down it one property at a time.
The last line prints { average: 8.7 }. Stopping one step short gives you the
inner object, not the number inside it.
Reading what might not be there
A path only works while every step exists. Reading a property off undefined
throws an error.
This show has no network, so show.network.name throws a TypeError.
show.network?.name gives undefined instead. That is optional chaining.
undefined is not something to show a reader, so ?? supplies a name to
display. let, const, and Scope covers why ?? and
|| disagree about what counts as missing.
Common mistakes
- Using dot notation with a variable key.
show.fieldlooks for a property calledfield; you wantshow[field]. - Reaching through a missing level.
show.network.namethrows whennetworkis missing, so writeshow.network?.name. - Trusting a typo to fail loudly. A misspelled property is
undefined, and the problem shows up further down.
Exercise
read should return the value stored under key, and fall back to "not set" only when the show has no such property. It prints not set four times
instead.
The output should read:
title: Severance
rating: 0
network:
missing: not set
The network line ends after the label, because an empty string is a real
value. Two things are wrong: how read looks up the key, and which fallback
operator it uses.