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 trial

JavaScript

edwinshen
edwinshen
13,168 Points

What's the difference between using destructuring to set default values in function parameters vs regular default values

Hello. I'm just a little bit confused why we would use destructuring in setting default values for function parameters vs just setting default values. What's the difference?

Setting default values:

function greet(name= 'Steven', timeOfDay = 'Day') {
    console.log(`Good ${timeOfDay}, ${name}!`); 
}

Here we just use equal signs to set the default parameters. But why do we use destructuring below?:

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

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

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

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,735 Points

If you're using destructuring, then it means you're passing in an object as an argument to the function. Default values you set in your destructuring will get used if that object doesn't have that property. If you're not using destructuring, it's because you're passing in arguments on their own, not as properties of an object.

function getItemsFromArgs(a = 1, b = 2) {
    console.log(`a: ${a}, b: ${b}`);
}

getItemsFromArgs(4); // a: 4, b: 2

In this case, it's the order of the arguments that matters. One argument is passed in, so it's assigned to the first parameter, which we've named a. There is no second argument so we'll use the default value from the 2nd parameter which is b.

function getItemsFromObject({ a = 1, b = 2 }) {
  console.log(`a: ${a}, b: ${b}`);
}

getItemsFromObject({b: 3}); // a: 1, b: 3

In this case, order doesn't matter. We're passing in one argument for one parameter, which are objects. The name we give the properties of the object when we pass in that object as an argument matches up with the properties we're destructuring.