Step 1 of 7 · Reading · ~3 min
Learn
Collections
Objects
An array finds things by position; an object finds them by name. By the end of this lesson you can build an object, read and change its properties by a name held in a variable, loop over it, and check safely whether a key is really there.
Creating and reading
An object is a set of key: value pairs, each pair called a property.
The distinction to remember: stock.fruit looks for a key literally named fruit, while stock[fruit] uses the value in the variable. Whenever the key comes from data, such as a word read from input, use brackets.
Adding, updating, removing
const locks the name stock, not the contents, so all of this is allowed on a const object.
Shorthand and methods
If a variable has the same name as the key, write it once. A function stored in a property is a method:
Objects can contain objects and arrays: shop.address.city, shop.tags[0].
Looping over an object
Keys that are not whole numbers come out in the order they were added. Keys that look like whole numbers ("1", "20") always come out first, in ascending order, no matter when they were added.
Is the key really there?
Every object inherits a few built-in properties, such as toString and constructor. The in operator and plain lookups see them too, so scores["constructor"] is a function, not undefined, even though you never added it. When the keys come from user data, test with hasOwnProperty (own keys only) before you trust a lookup.
Copying and comparing
Objects are handled by reference. const b = a; makes a second name for the same object, and === on two objects asks "the same object?", not "the same contents?":
Spread copies one level deep. Nested objects are still shared between the copy and the original.
Common mistakes
obj.keywhen the key is in a variable. It looks up the literal name; you needobj[key].if (obj[key])as an existence test: it fails for stored0,""andfalse, and wrongly succeeds for inherited names likeconstructor.- Expecting
===to compare contents. - Expecting
constto keep the contents fixed. - Relying on key order when the keys look like numbers.
Your exercise
Build a word dictionary out of input lines and use it to translate a sentence. The starter reads the pairs and the sentence; you fill the object and do the lookups. The sentence may contain any words, so think about words your dictionary does not know.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…