JavaScript: The Recent Parts

Parameter Objects

Kyle Simpson

Kyle Simpson

You Don't Know JS
JavaScript: The Recent Parts

Check out a free preview of the full JavaScript: The Recent Parts course

The "Parameter Objects" Lesson is part of the full, JavaScript: The Recent Parts course featured in this preview video. Here's what you'd learn in this lesson:

Kyle demonstrates how to apply destructuring when the function signature contains an object.


Transcript from the "Parameter Objects" Lesson

>> Kyle Simpson: Let's talk about the structuring of object parameters. Just like we talked about the structuring array parameters. If I have a function data that is receiving some temp variable and then I would be inclined to say a and b = tmp. And even if I put on the equals empty object here I'm still doing things the hard way by having to do a destructuring pattern inside of my body instead of up here on the parameter list.

So the equivalent then that would be better would be to say data and then do an object destructuring directly in the parameter position with my default,
>> Kyle Simpson: And say a and b.
>> Kyle Simpson: So that object in that parameter position, is not going to be captured in any way like it is over here with temp.

So if you actually need the thing, you need to go this route and capture it as a name, and then subdestructure it. But if you don't need access to the original object being pulled in and you only care about pulling out some of its contents, this is a much more declarative syntax.

>> Kyle Simpson: When you put an object in this parameter position, you're only accounting for one parameter to the data function. You're not accounting for all the parameters to it. You could pass another parameter after it, another argument after it, and that would go to a second parameter. So you could list a second parameter called x.

When you call the data function it would be expecting you to pass in an object as the first thing.
>> Kyle Simpson: And then it would be expecting you to pass something else for X like the number 42. But I would tell you that I have never had the occasion to do either an object or an array destructuring in a function parameter and then also have other parameters.

If I do an array, or an object destructuring in a parameter position, I'm gonna just end up passing all of my stuff inside of the object to the array, never as other separate arguments. That's up to you in terms of how you design stuff. But I find that to be super confusing, why would that be in a separate parameter, just make that thing be inside of the object and call it x, right?

And then it would be better for my call site to look like this.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now