Skip to content

Instantly share code, notes, and snippets.

@Ado77
Forked from ericelliott/defaults-overrides.md
Created September 7, 2018 14:07
Show Gist options
  • Select an option

  • Save Ado77/38ecabd853bd7a1fcacad2bdb9311147 to your computer and use it in GitHub Desktop.

Select an option

Save Ado77/38ecabd853bd7a1fcacad2bdb9311147 to your computer and use it in GitHub Desktop.
ES6 defaults / overrides pattern
// The defaults / overrides pattern in ES6
// This *looks like* it should work, but
// prints, "yay, undefined"
/*
let defaults = {
bar: 'no',
baz: 'works!'
};
function foo ({ bar, baz } = defaults) {
return(`${bar}, ${baz}`);
}
console.log(foo({
bar: 'yay'
}));
*/
// So you really have to do this:
let defaults = {
bar: 'no',
baz: 'works!'
};
function foo (options) {
let settings = Object.assign({}, defaults, options);
let { bar, baz } = settings;
return(`${bar}, ${baz}`);
}
console.log(foo({
bar: 'yay'
}));
// Equivalent to ES5:
// This bit needs to be polyfilled,
// Or use $.extend(), _.extend(),
// lodash/object/assign aka _.assign()
// or equivalent.
var assign = Object.assign;
var defaults2 = {
bar: 'no',
baz: 'works!'
};
function foo2 (options) {
var settings = assign({}, defaults2, options),
bar = settings.bar,
baz = settings.baz;
return(bar + ', ' +baz);
}
console.log(foo2({
bar: 'yay'
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment