ES6 Parameter Object Destructuring with Required Values

Elijah Manor
InstructorElijah Manor
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 years ago

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

[00:01] 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.

[00:20] 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.

[00:33] 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."

[00:54] 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.

[01:17] 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.

Denis Stoyanov
Denis Stoyanov
~ 8 years ago

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)

Slo Cha
Slo Cha
~ 7 years ago

dude. that was smooth. i like this trick.

Mike
Mike
~ 7 years ago

Awesome! Very clever.

Markdown supported.
Become a member to join the discussionEnroll Today