Passing argument name when calling function in javascript

I have a function that looks like this:

function helo(a,b){ if(a) { //do something } if(b) { //do something } } 

Now, if I want to specify which parameter should be passed when helo is called, how to do it in javascript, i.e.

If I want to send only parameter b, how can I call the helo function?

 helo(parameterB); 

Parameter a is currently set to

+2
source share
4 answers

It is best to simply pass an object containing all the parameters:

 function myFunction(parameters){ if(parameters.a) { //do something } if(parameters.b) { //do something } } 

Then you can call the function as follows:

 myFunction({b: someValue}); // Nah, I don't want to pass `a`, only `b`. 

If you want to be able to pass falsy values ​​as parameters, you will have to change if a bit:

 if(parameters && parameters.hasOwnProperty('a')){ //do something } 

Another option is to simply pass null (or any other falsy value) for parameters you don't want to use

 helo(null, parameterB); 
+9
source

In JavaScript, parameters are mapped in order, so if you want to pass only the second parameter, you must leave the first empty

 helo(null,parameterB); 
+2
source

Instead of passing several different arguments, you can pass one argument, which is an object.

Example:

 function helo(args){ if(args.a){ ... } if(args.b){ ... } } helo({b: 'value'}); 
0
source

You can use either of the two syntaxes:

 helo(null,parameterB); 

or

 helo(undefined,parameterB); 
0
source

Source: https://habr.com/ru/post/1275538/


All Articles