Last active
November 14, 2019 14:18
-
-
Save iandesj/cac21e23304d8ed78b3fcc4e9f61e9fb to your computer and use it in GitHub Desktop.
Examples of object destructuring vs direct object key-value access
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const taxPayer = { | |
firstName: 'Ian', lastName: 'DesJardins', | |
ssn: '123-45-6789', pastDue: true, | |
}; | |
console.log('Object destructuring example'); | |
// destructure the taxPayer object into new variables | |
const { firstName, lastName, ssn, pastDue } = taxPayer; | |
console.log('firstName =', firstName); | |
console.log('lastName =', lastName); | |
console.log('ssn =', ssn); | |
console.log('pastDue =', pastDue, '\n'); | |
// may also be used to destructure an object for a function's parameter | |
function parseTaxPayer({firstName, lastName, ssn, pastDue}) { | |
console.log('inside parseTaxPayer()'); | |
console.log('firstName =', firstName); | |
console.log('lastName =', lastName); | |
console.log('ssn =', ssn); | |
console.log('pastDue =', pastDue); | |
} | |
parseTaxPayer(taxPayer); | |
console.log('\nObject key access example') | |
// this is the equivalent of destructuring | |
const firstNameAgain = taxPayer.firstName; | |
const lastNameAgain = taxPayer.lastName; | |
const ssnAgain = taxPayer.ssn; | |
const pastDueAgain = taxPayer.pastDue; | |
console.log('firstNameAgain =', firstNameAgain); | |
console.log('lastNameAgain =', lastNameAgain); | |
console.log('ssnAgain =', ssnAgain); | |
console.log('pastDueAgain =', pastDueAgain, '\n'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment