- Named parameters in JavaScript and ECMAScript 6
- Named arguments | JS
- Taking advantage of ES6 Destructuring
- Standard arguments 🆚 Named arguments
- Standard arguments
- Named arguments
- Warning
- (Bonus track) Use the same good practice with returning values
- Related articles
- Day.js | The lightest API to handle dates in JS
- Code smell | Hardcoded fake data in tests
- Design pattern | Criteria
- Javascript function argument names
Named parameters in JavaScript and ECMAScript 6
Warning: This blog post is outdated. Instead, read section “Named parameters” in “JavaScript for impatient programmers”.
This post explains what named parameters are, how they can be simulated in JavaScript, and what improvements ECMAScript 6 will bring. Obviously, what is said about methods here applies to functions, as well.
Positional parameters and named parameters. When calling a method in a programming language, the actual parameters (specified by the caller) have to be mapped to the formal parameters (of a method definition). There are two common ways to do so:
- Positional parameters are mapped by position: The first actual parameter is mapped to the first formal parameter etc.
- Named parameters use names (labels) to perform the mapping. Names are associated with formal parameters in a method definition and label actual parameters in a method call. It does not matter in which order named parameters appear, as long as they are correctly labeled. The following sections explain why named parameters are useful and give examples.
What do these two numbers mean? Python supports named parameters and they make it easy to see what is going on:
Named parameters and options. The optional parameters of a method are sometimes called its options. Positional parameters are awkward if parameters can be omitted anywhere (not just at the end). Then any subset of the options can be active and one often has to insert blanks such as null for the inactive ones. Named parameters help with options in two ways: They clearly describe what parameters are active and they allow one to simply drop the inactive ones.
JavaScript. JavaScript does not have native support for named parameters like Python and many other languages. But there is a reasonably elegant simulation: provide optional parameters via an object literal. The result is a so-called options object that is assigned to a single formal parameter. Using this technique, an invocation of select() looks as follows:
The method receives an options object with the properties from and to. You can drop any of the options:
entries.select(< from: 3 >); entries.select(< to: 5 >); entries.select();
Obviously, you could also introduce positional parameters. It is customary for the options to come last, but JavaScript does not force you to do so.
entries.select(value1, value2, < from: 3, to: 5 >);
Entries.prototype.select = function (options) < if (options === undefined) options = <>; if (options.from === undefined) options.from = 0; if (options.to === undefined) options.to = this.length; // Use options.from and options.to >;
Not particularly elegant. It can be shortened a little, but then you have to worry about what values JavaScript considers to be false:
Entries.prototype.select = function (options) < if (!options) options = <>; if (!options.from) options.from = 0; if (!options.to) options.to = this.length; // Use options.from and options.to >;
EcmaScript 6. In ECMAScript 6 (ES6), we get a much more comfortable solution (reminder via Brendan Eich):
Entries.prototype.select = function ( < from = 0, to = this.length >) < // Use `from` and `to` >;
Allen Wirfs-Brock points out that if you want people to be able to omit the options object then the above changes to:
Entries.prototype.select = function ( < from = 0, to = this.length >= <>) < // Use `from` and `to` >;
JavaScript engines should be able to optimize invocations of functions and methods with ES6-style named parameters such that no temporary object is created.
Named arguments | JS
Today I am writing again to present a good practice that I discovered a short time ago and that I have been applying since then in any project that uses JavaScript. In this post we will see what the named arguments are and how they can help us to make code cleaner. Lets goo!!
Taking advantage of ES6 Destructuring
Destructuring is a functionality that is included with ES6, this functionality allows us to create simpler and more readable code, we will see an example of use before entering with the named arguments
const food = tomato: 'tomato', banana: 'banana' > // use destructuring for get values, order doesn’t matter const banana, tomato > = food console.log(tomato) // output: "tomato"
Standard arguments 🆚 Named arguments
To make the comparison of how the arguments behave in both cases we will use a function called createProduct()
Standard arguments
In this case we will use the arguments in the standard way, we will also introduce a argument called priceInEur with a default value of 1
/* Create a function with named arguments */ function createProduct( name, priceInEur = 1, weightInKg, heightInCm, widthInCm ) // functionality > // call function and passing args createProduct('cookies', undefined, 20, 10, 10)
Here we observe one of the first drawbacks and that is that we need to pass an undefined value to preserve the order of the arguments defined in the function and so that it has its default value
Named arguments
For this example we will use the same function but in this case we will use the named arguments
/* Create a function with named arguments */ function createProduct( name, priceInEur = 1, weightInKg, heightInCm, widthInCm >) // functionality > // call function and passing args createProduct( name: 'cookies', //priceInEur | set default value if not passed weightInKg: 20, heightInCm: 10, widthInCm: 10 >)
As we can see what we call named arguments is nothing more than a destructuring of the keys of an object that in this case will act as «arguments» of the function.
Being a destructuring of an object we can take advantage of its advantages and for example dispense with optional arguments, change the order of the object’s properties and some more things that we will see now
✅ Advantages | ❌ Disadvantages |
---|---|
The order of the arguments does not matter since we are dealing with an object | May lead to creating functions with many arguments |
No need to pass optional arguments to undefined | The code will be larger since you have to add the keys and values of the object that you send by argument |
Improve the extensibility and maintainability of our code | |
Improve legibility | |
provide more context to your arguments |
Warning
As we can see, it is a practice that is not complex to apply, but it is not good to abuse it either, especially in functions where a single argument is used and also this is self-descriptive by the name of the function, for example:
✅ function getProductById(id) // code. > ❌ function getProductById( id >) // code. >
(Bonus track) Use the same good practice with returning values
function getProductById(id) const response = null, error = null, loading = false // code. return response, error, loading > > // use this way const response, error, loading > = getProductById(1)
Related articles
Day.js | The lightest API to handle dates in JS
Library that will help us with the handling of dates in JavaScript.
Code smell | Hardcoded fake data in tests
this code smell occurs when you see fake data that is needed for tests within the same test file.
Design pattern | Criteria
This pattern allows you to build search queries using a common interface, which makes the code much more modular and flexible.
Javascript function argument names
Skipper: We’ll fix it.
Alex: Fix it? How you gonna fix this?
Skipper: Grit, spit and a whole lotta duct tape.
Thank you for your comments, Peter.
First of all, your advice to the users is the most wise and, at the same time, very universal, could be applied to most techniques.
First of all, perhaps you should not take all this matter too seriously. This is not really a method passing algorithm, just a pure textual fake. This is just the «property assignment» semantic disguised as a list of parameters. Probably, by «approach forces to use named arguments in any case» you mean that the user of the function, the person who would write the call, would not be able to choose between named and positional syntax. Is so, this is true. (How else, if the list is not a «real» list of parameters? But it has nothing to do with default values. Yes, you can leave values to defaults by not assigning anything to any of the parameters. One is «forced» to use named syntax no matter if defaults are used or not.
I also would challenge you to proof your note «forced prefix will cause some troubles». «Some» sounds too indefinite to me. If you can see some troubles, please openly write about those and provide clear explanation.
Also, agree on some performance price, but not sure it could possibly be significant, on the background of the performance price of interpretive nature of the language (which is, by the way, not 100% interpretive, as lexical analysis of the whole script comes first). After all, performance price is the commonplace.
It wasn’t about technical problems at all, but about the human factor . I’ve seen much who had a very hard time to meet some guidelines even were good at the language. My thought was, about one who try to introduce it to his team of seasoned JS developers.
That’s exactly. Before then you had only positional, and now you have only named. Both are missing a lot.
My problem is here, that in normal usage of JS (inside a web page), most functions are called a very few times, most of them only once, but those wrappers (and the resulting closures) are created each time your class (library?) loaded. That’s a lot of wasted time. If it was a requirement from me I would like to look for a JIT solution (and I say that without even checking the possibilities of that). That would make it a much better bargain.
All in all. All I wanted to say — not to you, but to those considering your approach — is that there are more things to and one should look around — always.
But, your solution can be the right-tool if carefully considered.
Skipper: We’ll fix it.
Alex: Fix it? How you gonna fix this?
Skipper: Grit, spit and a whole lotta duct tape.
Thank you for all the clarifications.
Perhaps you should also understand the meaning of this exercise: «This is what’s given. What can we possibly do about it?»
Actually, your warning addressed to the users is quite valid. And the deficiency of both «positional only» and «named only» choices is a really good point. And I did not try to convince people to use this approach. Rather, it could serve as a food for thought at the expressive capabilities of languages in general and their values.
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.