Object Destructuring

Object Destructuring
πŸ‘¨β€πŸ’Ό We're building a user profile system. Instead of accessing properties one by one with user.name, user.email, etc., let's use destructuring for cleaner code.
// Instead of this:
const name = user.name
const email = user.email

// Do this:
const { name, email } = user

Renaming Variables

Sometimes you need a different variable name:
const { name: userName, email: userEmail } = user
// userName = user.name, userEmail = user.email

Default Values

Provide fallbacks for potentially missing properties:
const { nickname = 'Anonymous' } = user
// Uses 'Anonymous' if user.nickname is undefined
🐨 Open
index.ts
and use the provided user fixture:
  1. Destructure name and email from user (expected: 'Alice Johnson', 'alice@example.com')
  2. Destructure id renamed to userId (expected: 'u123')
  3. Destructure bio with default 'No bio provided' (expected that string, because user has no bio)
  4. Create formatUserCard that destructures name, email, and role from its parameter and returns a string that includes all three of those values
  5. Export name, email, userId, bio, and formatUserCard
πŸ’° You can rename fields and provide defaults while destructuring.

Please set the playground first

Loading "Object Destructuring"
Loading "Object Destructuring"