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!
source to share
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.
source to share
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...
}
source to share