Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript skip arguments in function call

Tags:

javascript

javascript beginner here.

Let's say I'm having a javascript function that takes 3 arguments:

function f(arg1, arg2, arg3) { // do stuff }

I know that I can call f(value1, value2); and in that case inside the function scope arg1 will be value1, arg2 will be value2 and arg3 will be null.

Everything ok with this. However if I want to call the function giving values only to arg1 and arg3 I need to do something like this: f(value1, null, value2);

Is there a way I can specify which arguments to have which values in a more C#-esque manner (without specifying not given arguments as null)? Something like this: for calling f with values only for arg1 and arg3 I would write f(value1, arg3 = value2);

Any ideas? Cheers!

like image 393
Vee6 Avatar asked Sep 03 '14 11:09

Vee6


4 Answers

Yes you can. It can be written as:

f(arg1, undefined, arg3);

In this call, arguments 1 and 3 will pass, and argument 2 will not be sent.

like image 105
Ali Avatar answered Nov 13 '22 11:11

Ali


With ECMAScript 6 (ECMAScript 2015) and the introduction of Default Parameters, it can be as easy as setting default values to the parameters and passing undefined to skip a parameter:

function paramsTest(p1 = "p1 def", p2 = "p2 def", p3 = "p3 def") {
  console.log([p1, p2, p3]);
}

paramsTest(); // [ "p1 def", "p2 def", "p3 def"]
paramsTest("p#1", "p#2"); // [ "p#1", "p#2", "p3 def"]
paramsTest("p#1", undefined, null); // [ "p#1", "p2 def", null]
like image 23
CicheR Avatar answered Oct 22 '22 23:10

CicheR


there is a way i have seen for this:

for example

function person(name,surname,age)
{
...
}

person('Xavier',null,30);

you can do this:

function person(paramObj)
{
   var name = paramObj.name;
   var surname = paramObj.surname;
   var age = paramObj.age;
}

calling like this:

person({name:'Xavier',age:30});

I think this is the closest you'll be able to do it like in c# have in mind that JS is not compilled so you can't predict the arguments of a function.

EDIT:

For better syntax you can use ES6 object destructuring, like this:

function person({name, surname, age})
{
   ...
}

https://javascript.info/destructuring-assignment

like image 15
Manjar Avatar answered Nov 13 '22 09:11

Manjar


If you were going to do (let's say it was valid)

f(value1, arg3 = value2)

Then argument 2 would be undefined, so just pass that:

f(value1, undefined, value2)
like image 3
George Avatar answered Nov 13 '22 10:11

George