Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 1071 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

ES6 Parameter Object Destructuring with Required Values

1:40 JavaScript lesson by

Not only can you provide default values when using ES6 parameter object destructuring, but you can also require the presence of certain properties

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

Not only can you provide default values when using ES6 parameter object destructuring, but you can also require the presence of certain properties

Avatar
Ihor

Great example! Could you please explain how & why it works? :)

In reply to egghead.io
Avatar
Denis Stoyanov

I think you should provide this article http://www.2ality.com/2016/05/six-nifty-es6-tricks.html (Probably this is source where you got this approach)

Avatar
activedecay

dude. that was smooth. i like this trick.

Avatar
Mike

Awesome! Very clever.

What we have here is an AJAX function using ESX parameter object to structuring and we're providing default values. As you can see, when we call our AJAX function we're getting not only the values we passed into the function, but we're also getting default values for the things we didn't pass like type, data, and is async.

We could, at this point, remove the URL and success properties when calling the AJAX function, and you'll see we're providing default values for them, but that doesn't seem quite right. Those properties should probably be required, so let's do that.

What we're going to do is come up here and create a new function called required parameter, and give it a name of parameter. Then we're going to throw a new error, and it will say, "Missing parameter." It'll say, "Name."

Instead of setting a default value for the URL property, we're going to call our required parameter function instead. What will happen is, if our AJAX function is called without a URL property, the required parameter function will be invoked instead resulting in an error exception saying, "Missing parameter URL." Likewise, we could do the same thing for the success property.

Now, if we try to call the AJAX function with only the URL property, we should see a missing parameter exception for the success property. If we provide a value for the success property, then we should see all of our parameters logged to the console. By leveraging the default value feature of object destructuring to our advantage, we could provide required parameters as you've seen demonstrated.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?