Skip to content

Instantly share code, notes, and snippets.

@niklas-r
Last active August 29, 2015 14:28
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 niklas-r/ab849b958b52048b71f9 to your computer and use it in GitHub Desktop.
Save niklas-r/ab849b958b52048b71f9 to your computer and use it in GitHub Desktop.
Argument object with default properties and values in ES2015
function f({a = "I'm A", b = "I'm B"} = {}) {
console.log(a); // >"I'm C"
console.log(b); // >"I'm B"
}
f({ a: "I'm C" });
@niklas-r
Copy link
Author

Thanks to destructuring and default parameters, it's possible to have a function accept an object with default properties and values.

I like how compact the syntax is. To achieve similar functionality with ES5 I've previously done something like this:

function f(settings) {
  var a = (typeof settings.a !== 'undefined') ? settings.a : "I'm A";
  var b = (typeof settings.b !== 'undefined') ? settings.b : "I'm B";

  console.log(a); // >"I'm C"
  console.log(b); // >"I'm B"
}

f({ a: "I'm C" });

It's also possible to extend the settings object with a defaults object with the help of a library function. But as you can probably tell, both of those solutions will become rather messy when you have a few more default key/values in your settings object.

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