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
and use the provided
user fixture:- Destructure
nameandemailfromuser(expected:'Alice Johnson','alice@example.com') - Destructure
idrenamed touserId(expected:'u123') - Destructure
biowith default'No bio provided'(expected that string, becauseuserhas nobio) - Create
formatUserCardthat destructuresname,email, androlefrom its parameter and returns a string that includes all three of those values - Export
name,email,userId,bio, andformatUserCard
π° You can rename fields and provide defaults while destructuring.