Farsh Farsh - 1 month ago 8
Javascript Question

Large list of parameters in javascript constructors

My coach in the comments told me that here's large list of parameters, what did he mean?

function Product(id, name, cost, quantity, shortDescription, fullDescription) {
this.id = id;
this.name = name;
this.cost = cost;
this.quantity = quantity;
this.shortDescription = shortDescription;
this.fullDescription = fullDescription;
}

Answer

Your id, name, cost, quantity, shortDescription, and fullDescription are parameters (you'll frequently hear them called "arguments"1) to the Product function. He's saying six is too many. It's a matter of style and maintenance, and opinions may vary, but that's what he's saying.

You might consider using a single options parameter instead:

function Product(options) {
    this.id = options.id;
    this.name = options.name;
    this.cost = options.cost;
    this.quantity = options.quantity;
    this.shortDescription = options.shortDescription;
    this.fullDescription = options.fullDescription;
}

...which you would call by passing in an object with those properties on it, like this:

var p = new Person({
    id: 42,
    name: "Douglas Adams",
    cost: "Priceless",
    quantity: 0,
    shortDescription: "Great author",
    fullDescription: "Mostly harmless"
});

In ES2015 and higher, you can do that with destructuring parameters:

function Product({id, name, cost, quantity, shortDescription, fullDescription}) {
    // Note -----^-----------------------------------------------------------^
    this.id = id;
    this.name = name;
    this.cost = cost;
    this.quantity = quantity;
    this.shortDescription = shortDescription;
    this.fullDescription = fullDescription;
}

You still call it the same way, with an object:

let p = new Person({
    id: 42,
    name: "Douglas Adams",
    cost: "Priceless",
    quantity: 0,
    shortDescription: "Great author",
    fullDescription: "Mostly harmless"
});

Again: That's ES2015 and above.


1 parameters vs. arguments: In the declaration, the technically-correct term is "parameter." In the call, the term is "argument". E.g., here's a function taking a name parameter:

function foo(name) {
    // ...
}

...and here we are calling it with the argument "Douglas":

foo("Douglas");

In everyday speech, it's absolutely fine to talk about "the name argument" without making the parameter/argument distinction. But that's the distinction: The abstract thing in the declaration vs. the concrete thing in the call.

Comments