Last active
November 14, 2019 14:13
-
-
Save iandesj/615221be106c307c07a0c4dde0958335 to your computer and use it in GitHub Desktop.
Examples of array destructuring vs array index accessing
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 = [ 'Ian', 'DesJardins', '123-45-6789', true ]; | |
console.log('Array destructuring example'); | |
// destructure the taxPayer array 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 array for a function's parameter | |
function parseTaxPayerArray([firstName, lastName, ssn, pastDue]) { | |
console.log('inside parseTaxPayerArray()'); | |
console.log('firstName =', firstName); | |
console.log('lastName =', lastName); | |
console.log('ssn =', ssn); | |
console.log('pastDue =', pastDue); | |
} | |
parseTaxPayerArray(taxPayer); | |
console.log('\narray index access example') | |
// this is the equivalent of destructuring | |
const firstNameAgain = taxPayer[0]; | |
const lastNameAgain = taxPayer[1]; | |
const ssnAgain = taxPayer[2]; | |
const pastDueAgain = taxPayer[3]; | |
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