Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active May 7, 2023 13:52
Show Gist options
  • Save ericelliott/f3c2a53a1d4100539f71 to your computer and use it in GitHub Desktop.
Save ericelliott/f3c2a53a1d4100539f71 to your computer and use it in GitHub Desktop.
ES6 defaults / overrides pattern

ES6 Defaults / Overrides Pattern

Combine default parameters and destructuring for a compact version of the defaults / overrides pattern.

function foo ({
    bar = 'no',
    baz = 'works!'
  } = {}) {

  return (`${bar}, ${baz}`);
}

console.log(foo({
  bar: 'yay'
})); // logs 'yay, works!'

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'
})); // logs 'yay, works!'

Gist written for How to Use ES6 for Isomorphic JavaScript Apps

@marcelo-ribeiro
Copy link

👍

@mathieug
Copy link

mathieug commented Mar 5, 2018

Nice trick @ericelliott! How can we name the object parameter if we need an object with all the parameters (given and default)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment