Object Destructuring is a little bit of syntactic sugar ✨ that can be used to bind the properties of an object to a variable. Sometimes working with JavaScript objects can become repetitive in the sense that you need to write out the object name followed by the property name like so: objectName.propertyName. Using object destructuring, you can simply use propertyName to achieve the same result.

Syntax 📝

const { propertyName } = objectName;

Real-World Examples 🌎

Let's say that we have a JavaScript object that represents an athlete. As you could imagine, there's plenty of properties that could be added to any given athlete. For example:


const newEnglandPatriots = {

    stadium: 'Gillette Stadium',
    location: 'Foxboro, Massachusetts',
    superBowlsWon: 6,
    teamOwner: 'Robert Kraft',
    headCoach: 'Bill Belichick',
    roster: {
        quarterBack: {
            firstName: 'Tom',
            lastName: 'Brady',
            jerseyNumber: 12,
            isTheGreatestOfAllTime: true,
            throwTouchdown: function(){ 
                return 'Touchdown!' 
            } 
        }
    }

}

// instead of this
newEnglandPatriots.roster.quarterBack.isTheGreatestOfAllTime // returns true

// you can destructure the object like so
const { isTheGreatestOfAllTime } = newEnglandPatriots.roster.quarterBack;

// now the property is bound to a variable, and much shorter 
isTheGreatestOfAllTime // returns true

// you can bind multiple properties at once, too
const { teamOwner, headCoach } = newEnglandPatriots

teamOwner // returns 'Robert Kraft'
headCoach // returns 'Bill Belichick'

// you can also bind methods
const { throwTouchdown } = newEnglandPatriots.roster.quarterBack;

throwTouchdown() // returns 'Touchdown!'

Test this code in your browser console

Wrapping Up ✅

Object Destructuring is a great way to make your code cleaner and less repetitive. Not to mention, the syntax is pretty straightforward. Go Pats! 🏈

Stay Tuned 📺

If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at tim@timwheeler.com. If you're enjoying my posts, please subscribe below! 👇