Quiz
Warm-up from lesson 4-2: you built a shopping list with push. What does list.pop() do AND give back?
Objects are JavaScript's dictionaries
Arrays handle many-of-the-same-thing; objects handle one-thing-with-many-facts. A user has a name, an age, a plan; a product has a title and a price. Nearly every piece of data a server will ever send you (lesson 5-3) arrives in this shape, so reading and writing it has to become reflex.
An array numbers its items. An object names them. It is JavaScript's version of the Python dict you used for labeled data:
const user = { name: "Ada", age: 36, premium: true };
Each name: value pair is a property. Unlike Python dicts, the keys are written without quotes (they are allowed, just not needed for normal names).
Reading has two spellings:
- Dot notation, the everyday one:
user.name - Bracket notation, for keys stored in variables or keys with odd characters:
user["age"]oruser[someKey]
Writing works the same way. Assigning to a property that does not exist yet simply creates it, and delete user.premium removes one. Like arrays, a const object can still have its contents changed.
Code exercise · javascript
Run it. Reading with dot and bracket, updating a property, and adding a brand new one. Printing the whole object shows every property.
Code exercise · javascript
Your turn. Create a book object with title Dune and pages 412. Print the sentence Dune has 412 pages using a template literal (from lesson 1-3). Then add an author property set to Frank Herbert and print it.
Quiz
You have const key = "email" and want to read that property from user. Which works?