Destructuring JavaScript Configuration Objects

Destructuring Assignment In Javascript introduces the concept and syntax of destructuring assignment, but leaves an important question unanswered: Why should you care?

Here’s one scenario where it might be nice: when you’re using configuration objects.

Lots of JS functions take a single object with multiple optional properties. You might think of these as “configuration objects” or “options parameters” or something along those lines.

Think about when you do this:

  url: 'https://localhost/getSomeStuff',
  cache: false,
  dataType: 'json',
  timeout: 5000

You’re passing a bunch of values into $.ajax via properties of the single object you pass into it. Each of those properties is optional. (But $.ajax does have default values for all those things.)

What does $.ajax have to do to handle those things? (I’ll butcher this. Bear with me.)

function ajax(options) {
  options = options !== undefined ? options : {};
  let url = options.url !== undefined ? options.url : '';
  let cache = options.cache !== undefined ? options.cache : true;
  let dataType = options.dataType !== undefined ? options.dataType : 'text';
  let timeout = options.timeout !== undefined ? options.timeout : 0;

  // now do stuff...

It takes the single options parameter and defines a bunch of local variables from properties of options, falling back to default values when those properties aren’t present. Then it does its AJAX-y magic, blah blah blah.

Destructuring assignment and default parameters can make this a little cleaner:

function ajax({
  url = '',
  cache = true,
  dataType = 'text',
  timeout = 0
} = {}) {
  // now do stuff...

This version of ajax replaces the options parameter from our first implementation with a destructuring assignment that defines and initializes the local variables url, cache, dataType and timeout. Clearly there’s much less code here. Lots of folks will find this version preferable.