Chapter 7 of 34
~11 minObjects & Object Methods
Objects are collections of key-value pairs and are how you model just about anything with structure in JavaScript - a user, a config, a shopping cart item. Knowing how to read, write, and reshape them fluently is essential.
Object Literals and Property Access
You create an object with curly braces: `const user = { name: 'Sam', age: 30 }`. You can read or write properties with dot notation (`user.name`) when the key is a valid identifier, or bracket notation (`user['name']`) when the key is dynamic or has special characters.
Try it yourself
Dot vs bracket notation<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Methods and Shorthand
A function stored as a property is called a method. ES6 shorthand lets you write `{ name, age }` instead of `{ name: name, age: age }` when the variable name matches the key, and lets you define methods as `greet() { ... }` instead of `greet: function () { ... }`.
Try it yourself
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Object.keys, values, and entries
`Object.keys(obj)` returns an array of an object's own property names. `Object.values(obj)` returns the values. `Object.entries(obj)` returns `[key, value]` pairs, which is especially handy for looping with `for...of` or converting to a `Map`.
Try it yourself
Iterating an object<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Destructuring and the Spread Operator
Object destructuring pulls properties into named variables: `const { name, age } = user`. The spread operator `{ ...user }` creates a shallow copy of an object, which is the standard way to update state immutably (e.g. `{ ...user, age: 31 }` produces a new object with just `age` changed).
Coding challenge
Create an object book with title and author properties. Use the spread operator to create a new object updatedBook that has the same title but a different author, without mutating the original. Log both objects.
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/41. When must you use bracket notation instead of dot notation to access a property?
2. What does `Object.entries(obj)` return?
3. What kind of copy does `{ ...obj }` create?
4. What is the ES6 shorthand for `{ name: name, age: age }` when variables `name` and `age` already exist?