Skip to content

Instantly share code, notes, and snippets.

@alperg
Last active October 17, 2019 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alperg/1ce392593e4c094720e00b67d4169192 to your computer and use it in GitHub Desktop.
Save alperg/1ce392593e4c094720e00b67d4169192 to your computer and use it in GitHub Desktop.
Default props
// 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