Last active
October 17, 2019 15:52
-
-
Save alperg/1ce392593e4c094720e00b67d4169192 to your computer and use it in GitHub Desktop.
Default props
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
// Default properties are values that will be set only when they are not included in the original object. | |
// In this example, user2 does not contain quotes. The setDefaults function ensures all objects have quotes set otherwise it will be set to []. | |
// When calling setDefaults(user2), the return value will include quotes: []. | |
// When calling setDefaults(user4), because user4 already has quotes, that property will not be modified. | |
const user2 = { | |
id: 200, | |
name: 'Vince Noir' | |
}; | |
const user4 = { | |
id: 400, | |
name: 'Bollo', | |
quotes: ["I've got a bad feeling about this..."] | |
}; | |
const setDefaults = ({ quotes = [], ...object}) => | |
({ ...object, quotes }); | |
setDefaults(user2); | |
// { id: 200, name: 'Vince Noir', quotes: [] } | |
setDefaults(user4); | |
// { | |
// id: 400, | |
// name: 'Bollo', | |
// quotes: ["I've got a bad feeling about this..."] | |
// } | |
// It can also be written like this if you want the defaults to appear first instead of last: | |
const setDefaults = ({ ...object}) => ({ quotes: [], ...object }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment