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
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
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
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:
(Bonus track) Use the same good practice with returning values
Thanks for reading me. π