Javascript skipping arguments in function call

javascript beginner here.

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

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

      

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

Everything is good. However, if I want to call a function that gives values ​​only arg1

and arg3

, I need to do something like this f(value1, null, value2)

:;

Is there a way to specify which arguments should have which values ​​in a more C #-esque manner (without specifying unspecified arguments as null)? Something like this: to call f with values ​​only for arg1

and arg3

I would writef(value1, arg3 = value2);

Any ideas? Hooray!

+3


source to share


5 answers


there is a way i saw for this:

eg

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

person('Xavier',null,30);

      

You can do it:



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

      

calls the following:

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

      

I think this is the closest that you will be able to do this, as in C # keep in mind that JS does not compile, so you cannot predict the function arguments.

+5


source


The only way you could do it with JS is to pass one array containing all the parameters.

The default values ​​must be set inside the function - you cannot define default values ​​for arguments in JavaScript.

function foo( args ){
  var arg1 = args[ 0 ] || "default_value";
  var arg2 = args[ 1 ] || 0;
  ///etc...
}

      



Better yet, instead of an array, you can pass a simple object that will allow you to access the arguments by their key in the object:

function foo( params ){
  var arg1 = params[ "arg1" ] || "default_value";
  var arg2 = params[ "arg2" ] || 0;
  ///etc...
}

      

+2


source


If you are going to do (say it really is)

f(value1, arg3 = value2)

      

Then argument 2 will be undefined, so just pass this:

f(value1, undefined, value2)

      

+1


source


Yes, you can. It can be written as:

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

      

Arguments 1 and 3 are passed in this call, and argument 2 will not be sent.

+1


source


Add this code to your function (for default values)

function f(a, b, c)
{
  a = typeof a !== 'undefined' ? a : 42;
  b = typeof b !== 'undefined' ? b : 'default_b';
  a = typeof c !== 'undefined' ? c : 43;
}

      

call a function like this

f(arg1 , undefined, arg3)

      

0


source







All Articles