C
JavaScript/Objects & Arrays/Lesson 11

Object Essentials — Creation · Access · Destructuring · Spread

45 min·theory
This chapter
1/2

Object Essentials — Creation · Access · Destructuring · Spread

🎯 After reading this lesson

After finishing this lesson, you will be able to confidently do the following 3 things.

  • ✅ Destructuring + default values + rename + rest patterns
  • ✅ Immutable updates with spread + shallow copy limitations
  • ✅ Optional chaining ?. + ?? default value combination

Keep the learning objectives as a checklist and close the lesson once you can answer all of them.

Creating and Accessing Objects — Dot vs Bracket Notation

Object Literals

javascript
const user = {
    id: 1,
    name: 'Alice',
    email: '[email protected]',
    profile: {
        avatar: 'https://...', 
        bio: 'Developer'
    }
};

The most commonly used form. Almost identical to JSON, but keys can omit quotes (JS literals only).

Dot Notation vs Bracket Notation

javascript
console.log(user.name);       // 'Alice'   ← dot notation is convenient when the key is fixed
console.log(user['name']);    // 'Alice'   ← bracket notation works the same

// 🔑 Only bracket notation works when the key name is stored in a variable
const key = 'email';
console.log(user[key]);       // '[email protected]'
// user.key  → undefined (it looks for a property literally named "key")

// Nested access — both approaches are equivalent
console.log(user['profile']['bio']);   // 'Developer'
console.log(user.profile.bio);         // 'Developer'

Rule: Use dot notation when the key is a fixed string. Use bracket notation for dynamic keys.

When the Key Violates Identifier Rules

javascript
const data = { 'user-id': 1, 'first name': 'A' };
data.user-id    // ❌ Error (interpreted as subtraction)
data['user-id'] // ✅

When an API response has kebab-case keys, bracket notation is required.

Modify · Add · Delete

javascript
user.age = 30;            // ➕ New key → added
user.name = 'Bob';        // ✏️ Existing key → value updated
delete user.email;        // 🗑️ Removes the key entirely

console.log(user);
// { id: 1, name: 'Bob', profile: {...}, age: 30 }
//   ↑ name changed  ↑ email removed    ↑ age added

Shorthand Properties

javascript
const name = 'Alice', age = 30;
const u = { name, age };   // = { name: name, age: age }

When the variable name matches the key, you can omit the repetition. This is the basis for the <Comp {...props} /> pattern in React.

Destructuring Assignment — *The Essential Vocabulary for Vibe Coding*

Basic Destructuring

javascript
const user = { id: 1, name: 'A', email: '[email protected]' };

const { name, email } = user;
console.log(name);    // 'A'

Extract only the keys you need from an object into variables. This appears in every function signature in AI-generated code.

Renaming

javascript
const { name: userName } = user;
console.log(userName);   // 'A'

Default Values — When a Key Is Missing or undefined

javascript
const { name, role = 'user' } = user;
// If 'role' is not present in user, 'user' is used as the default

Nested Destructuring

javascript
const { profile: { bio } } = user;   // Extract only bio

In Function Parameters — The React Component Standard

javascript
// ❌ Old style
function Card(props) {
    return <div>{props.title}</div>;
}

// ✅ Destructuring
function Card({ title, subtitle, onClick }) {
    return <div>{title}</div>;
}

// ✅ Default value + rest
function Card({ title, subtitle = 'None', ...rest }) {
    return <div {...rest}>{title}</div>;
}

99% of React code worldwide uses this pattern. If you can't read it, every component looks like a foreign language.

Array Destructuring

javascript
const [first, second, ...rest] = [10, 20, 30, 40];
console.log(first, second, rest);   // 10 20 [30, 40]

const [a, , c] = [1, 2, 3];   // Skip the middle element → a=1, c=3

React's useState is the most frequently seen example of this syntax:

javascript
const [count, setCount] = useState(0);

Spread · Object Static Methods · Optional Chaining

Spread ... — Unpacking Objects

javascript
const user = { id: 1, name: 'A' };
const updated = { ...user, age: 30 };   // Spread all keys from user + add age

console.log(updated);   // { id: 1, name: 'A', age: 30 }
console.log(user);      // { id: 1, name: 'A' }   ← original unchanged! (immutable update)

The cornerstone of immutable updates. The standard pattern for updating React state:

javascript
setUser(prev => ({ ...prev, name: 'B' }));

Later keys overwrite earlier ones:

javascript
const merged = { ...defaults, ...userInput };  // userInput takes precedence

Shallow Copy Limitations

javascript
const original = { profile: { bio: 'Developer' } };
const copy = { ...original };
copy.profile.bio = 'AI';
console.log(original.profile.bio);   // 'AI' — changed together!

Only the first level is copied. Nested objects share references. For a deep copy:

javascript
const deep = structuredClone(original);   // Standard (Node 17+, all modern browsers)
const deep2 = JSON.parse(JSON.stringify(original));  // Old approach (loses functions, Dates, undefined)

3 Object Static Methods

javascript
const u = { name: 'A', age: 30, role: 'admin' };

console.log(Object.keys(u));     // ['name', 'age', 'role']
console.log(Object.values(u));   // ['A', 30, 'admin']
console.log(Object.entries(u));  // [['name','A'], ['age',30], ['role',30]]
//                                    ↑ array of [key, value] pairs

entries is used when you need both key and value simultaneously in a loop:

javascript
for (const [key, value] of Object.entries(u)) {
    console.log(`${key}: ${value}`);
}

Optional Chaining ?.Essential for Parsing API Responses

javascript
const city = user?.address?.city;      // Won't throw even if address is missing
const first = list?.[0];               // Works with arrays too
const result = obj.fn?.();             // Works with function calls too

Without ?.:

javascript
const city = user && user.address && user.address.city;

5 words collapsed into 1. It always appears in AI-generated code.

Nullish Coalescing ?? — Default Values

javascript
const page = req.query?.page ?? 1;   // Use default only for null/undefined

Combining optional chaining results with a default value is a go-to pattern.

🤖 Try asking AI like this

  • "Refactor this function parameter using destructuring"
  • "Make this object update immutable using spread"
  • "Make this deep object access safe using optional chaining"

⚡ Try It Yourself — Destructuring · Spread · Object Methods

Five modern object patterns all at once.
✏️ JS 코드
📟 Console output
▶ Press the Run button
⚠️ Runs in a browser sandbox — only console.log() is supported; alert/fetch are not.
Object Essentials — Creation · Access · Destructuring · Spread - JavaScript