JavaScript Introducing ES2015 The Cooler Parts of ES2015 Destructuring

Ken S.
Ken S.
3,724 Points

In the destructuring-default-function.js example, in the first getData, why does = {} have to be added to the first arg?

Pretty much asked in the title:

I noticed the getData function takes first parameter {url, method = 'post'} = {}

The full function is this:

function getData({ url, method = 'post' } = {}, callback) { callback(url, method); }

getData({ url: 'myposturl.com' }, function (url, method) { console.log(url, method); });

Wondering what the point of the '= {}' is? It seems to work just fine without it? Its very confusing to put it there without a reason and I'm guessing there is, but it is never explained in the instructors commentary as he goes through it.

Thank you!

Robert Schaap
Robert Schaap
19,832 Points

The equals sign after an argument of a function basically declares a default argument. See and try to run the below. firstArg has {} as a default and secondArg has 9001. If no arguments are passed to the function when calling it, the default arguments are instead used.

Personally I don't use this much, but it maybe useful for functions which take multiple arguments, but where one is usually the same.

function destructure(firstArg = {}, secondArg = 9001) {
  console.log(firstArg)
  console.log(secondArg)
}

destructure();
Ken S.
Ken S.
3,724 Points

Thank you Robert, I managed to figure out that much in the next few hours, however it just seems pointless in this example since there is a second arg which must be a callback function that is not given a default value, so if you call:

getData();

It would fail. You'd have to go out of your way and invoke something like getData(undefined, function(url, method) {console.log(url, method)}); just for it to do anything at all...

Michael Shields
Michael Shields
10,759 Points

The syntax of the first parameter is to take advantage of destructuring for assigning default values. Seeing this in action with Object Classes versus constructor functions and setting default values for when you call a new instance of the Object might help make more sense of how destructuring is used and how flexible it can be in your code.

In this example, Guil is assigning the getData function a first parameter of an object with keys url and method with post as the default value for the latter.

Check out the videos on Structure of Class that Guil does, might also shed a light on this is still confused.