Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKen S.
3,838 PointsIn 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!
Ken S.
3,838 PointsThank 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...
1 Answer
Michael Shields
12,650 PointsThe 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.
Robert Schaap
19,836 PointsRobert Schaap
19,836 PointsThe 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 andsecondArg
has9001
. 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.