Reputation: 17586
I have a function
function test(name)
{
}
I call it with test("kanishka");
In one case, I want to pass two parameters (name
and age
) to this function:
test("kanishka",27);
In PHP, I can do this by setting a default value to age
:
test(name , age = NULL)
Is there any way in JavaScript to do this?
I tried
test(name , age = NULL)
but it gives errors.
I can declare 2 functions
test(name) and test(name , age = NULL)
but it duplicates the code.
Or I can change my previous function call which took one parameter to two parameters, giving a default value for age
:
test("kanishka" , 0)
but in this case I have to find all function call and change them.
Upvotes: 2
Views: 6618
Reputation: 196217
Just changing the definition of the function will work
function test(name, age)
{
}
All existing uses of the function will assign to age
an undefined
value..
Whenever you use a second parameter it will be assigned to the age
parameter.
If you want a default value change the function to
function test(name, age)
{
age = (age === undefined) ? 0 : age; // change 0 to the default value you want..
}
Update
There is now support for default parameters
function test(name, age = 0)
{
// age will be 0 if no second parameter is provided or it is undefined
}
Upvotes: 8
Reputation: 58611
You can use the arguments
object which holds all arguments passed to a function - regardless of if they are defined or not...
test(name){
var age = arguments[1] == undefined ? 0 : arguments[1]
// do stuff here
}
Upvotes: 1
Reputation: 39675
The "standard" way to provide default values for methods is to check whether the arguments have been supplied at the start of the method body:
function test(name, age)
{
age = typeof(age) != 'undefined' ? age : NULL;
...
}
Upvotes: 0
Reputation: 166031
You can either declare the function with the 2 arguments:
function test(name, age) {
//...
}
test("James"); //age will be undefined
test("James", 22); //age will be 22
Or you could forget about the parameters altogether and use the arguments
object:
function test() {
console.log(arguments[0]);
}
This way you can pass in as many arguments as you like, and access them through the arguments
object.
Upvotes: 1
Reputation: 501
basically you will do something like this
function foo(a, b)
{
a = typeof(a) != 'undefined' ? a : 42;
b = typeof(b) != 'undefined' ? b : 'default_b';
...
}
Upvotes: 4
Reputation: 37771
You can still call the method, even if you pass the wrong number of arguments. The "optional" argument will be set to undefined, which you can check for using an if statement.
Upvotes: 1