Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why named parameters are better than positional parameters in JavaScript

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail why the named parameters are better than the location parameters in JavaScript, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

1. What are location parameters?

You must be familiar with location parameters, even if you hear the name for the first time.

Function greet (firstName, lastName) {console.log (`Hello ${firstName} ${lastName} `);} / / expected usage greet ('Michael',' Scott'); const fName = 'Harry'; const lName =' Potter'; greet (fName, lName); / / incorrect usage const firstName = 'Erlich'; const lastName =' Bachman'; greet (lastName, firstName)

The greet function takes two parameters: firstName and lastName. The caller must ensure that firstName is the first parameter and lastName is the second parameter. The important point here is that the name of the parameter does not make any sense, and the only thing that matters is the order in which the parameter is passed.

This familiar method is called positional parameters. Usually, this is good when you pass one or two parameters, because it's hard to mess up the order of the parameters. But if you have to call a function that requires six parameters, it's hard to remember the order in which the arguments are passed. You do not want to pass a password instead of a username parameter.

two。 Location parameter problem

The location parameters are simple, but you will face some challenges.

(1) cannot skip the intermediate parameter /

Suppose you have changed the greet function so that it now requires three parameters: firstName, middleName, and lastName. Since many people don't have middle names, you want to set MiddleName as an optional parameter, and the only way to call the greet function using firstName and lastName is this method.

Greet ('Aditya', null,' Agarwal'); / / Correct ✅ greet ('Aditya',' Agarwal'); / / Incorrect ❌

You can't just provide firstName and lastName. This problem becomes more obvious when the number of optional parameters increases to 5. Now, you must provide 5 null to provide parameters after these parameters.

(2) adding types to location parameters is not so clean.

Nowadays, it is very common to add types to your utility. With positional parameters, you have no choice but to inline the type with the function definition. This might blur the code a little bit, and it would be even better if we could declare the type definitions of all parameters in one block.

(3) cause minor errors

Location parameters wrap a lot of hidden behavior, which may be the cause of subtle bug. Let's take a look at a common JS skill problem.

Const numbers = [1, 4, 8, 10]; console.log (numbers.map (parseInt)); / / you might think the result would be: [1, 4, 8, 10] / / this is the actual output: [1, NaN, NaN, 3]

Are you surprised? The reason for this strange output is hidden behind the location parameters. You will see that the map and parseInt functions hide some of their secrets in obvious cases.

Let's look at the code number.map (parseInt) again.

What's going on here?

We run the map function on the numbers array.

Map takes the first item of the array and passes it to parseInt.

Now, for the first item in the array (that is, 1), it will execute parseInt (1). Right.? Wrong!

In fact, map passes three parameters to its callback function. The first is the current item in the array, the second is the index of the item, and the third is the entire array. There is no problem in itself, but the real problem lies in the latter part.

Numbers.map (parseInt) is different from numbers.map ((item) = > parseInt (item)). You can assume that since the callback function only accepts the item parameter and passes it to parseInt, we can skip the additional steps. But the two are different: in the former, we pass all the data from map to parseInt, while in the latter, we pass only items.

You may not know, but the second parameter of parseInt is called cardinality. By default, the cardinality value is 10 (based on 10, because humans follow the decimal system for counting). There is something wrong with this code, which is that we pass the index of the current project to parseInt as the cardinality value. These are the actual function calls that occur:

ParseInt ('1, 0, [...]); parseInt ('4, 1, [...]); parseInt ('8, 2, [...]); parseInt ('10, 3, [...])

Now that we know the problem, how can we do better?

3. Substitution of position parameter

What if a function can know what its expected parameters are by name? In this way, even if you missend extra data to it, it will only use what it needs.

Let's package the parseInt. Here is a simple implementation.

/ / implement function myCustomParseInt (objArgs) {return parseInt (objArgs.item, objArgs.radix);} / / use const num = myCustomParseInt ({item: '100 percent, radix: 10})

MyCustomParseInt accepts only one parameter, which is an object. This object can have two keys: item and radix. Let's use our custom function with map. There must be an intermediate step to send the args received by the callback to myCustomParseInt.

Const numbers = [1, 4, 8, 10]; const result = numbers.map ((item, index) = > myCustomParseInt ({item, index})); console.log (result); / / [1,4,8,10]

Note that even if we pass the index to myCustomParseInt, it won't cause any problems. That's because myCustomParseInt only ignores it. This pattern of passing objects to functions is called named parameters, which are more explicit than positional parameters.

To change the cardinality, we must explicitly pass the cardinality key. This means that if you want to parse a string with a base of 2, you must go to the document and see the exact name of the parameter (cardinality). It won't help if we pass any other keys blindly. This is great for us because it avoids unexpected behavior.

(1) with deconstructed named parameters

Not long ago, JavaScript acquired a feature called deconstruction, so let's use it in our myCustomParseInt implementation.

/ / position parameter function myCustomParseInt (item, radix) {return parseInt (item, radix);} / naming parameter old implementation function myCustomParseInt (objArgs) {return parseInt (objArgs.item, objArgs.radix);} / / deconstructing function myCustomParseInt ({item, radix}) {return parseInt (item, radix);}

You will notice that by adding two curly braces, we can get the benefit of naming args, and you can think of deconstruction as performing const item = objArgs.item;.

If you call myCustomParseInt using undefined, JS throws an error. That's because undefined.item is not allowed. To avoid this, we can add = {} at the end of the deconstruction. This way, when we pass the undefined, it will execute {}. Item, which is a valid JS. This is the final implementation:

Function myCustomParseInt ({item, radix} = {}) {return parseInt (item, radix);}

By naming the parameter pattern, we can also skip parameters that we do not want to provide, because the function is no longer dependent on the order in which the parameters are passed.

/ / for position parameters, we must add a null function greetPos (firstName, middleName, lastName) {} greetPos ('Aditya', null,' Agarwal') between them; / / using named parameters, you only need to provide firstName and lastName. Function greetNamed ({firstName, middleName, lastName} = {}) {} greetNamed ({firstName: 'Aditya', lastName' Agarwal'})

All in all, what I want to say is that named parameters are a powerful pattern that has become very common today, but you don't have to use them all the time. Sometimes you can even combine the two. The use of fetch API in the browser is as follows:

/ / the request that takes url as the location parameter, and the option to use args as the naming parameter. Fetch ('https://google.com', {method:' POST', headers: {'Content-Type':' application/json',},}); / / basic GET requests with just positional args fetch ('https://google.com');

The mandatory parameter (API path) here is a positional parameter, and then accepts the optional parameter by naming the parameter.

On why named parameters than location parameters in JavaScript is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report