Last active
November 25, 2021 21:51
-
-
Save timabell/0757735a759ed086fc57f51014392587 to your computer and use it in GitHub Desktop.
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
///// an exercise in object and array destructuring | |
// https://gist.github.com/timabell/0757735a759ed086fc57f51014392587 | |
// https://jsfiddle.net/sz479ecd/ | |
// object and array destructuring example | |
let sourceObject = { | |
propertyA: 2, | |
propertyB: [3, 4, 5], | |
z: 99, | |
}; | |
let { | |
propertyA: output1, // map property into new variable (seems backwards to me but that's how it is) | |
output2 = 6, // default for missing prop | |
propertyB: [ | |
output3, // capture first array element | |
...rest // dots capture remaining array elements | |
] = [], // default input to empty array to avoid "TypeError: (intermediate value).propertyB is undefined" if no input array | |
z, // make variable that matches property name | |
} = sourceObject || {}; // or default empty object to avoid "TypeError: sourceObject is undefined" if nothing passed in | |
console.log(output1, output2, output3, rest, z) | |
// again but with no source object so the defaults kick in | |
sourceObject = undefined; | |
( // surround with bracket because without the let it's not recognised as destructuring | |
{ | |
propertyA: output1, | |
output2 = 6, | |
propertyB: [ | |
output3, | |
...rest | |
] = [] | |
} = sourceObject || {}); | |
console.log([output1, output2, output3, rest.length, rest[0], rest[1]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment