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
- Use object destructuring to extract
nameandemailfrom a user object - Rename a property while destructuring (e.g.,
idtouserId) - Provide a default value for an optional property
π° Destructuring with rename and default:
const { id: productId, description = 'No description' } = product