Can you declare the arguments of an optional function in Javascript?
If you want to set a default value for your arguments, you can do something like this:
function whatever(arg1) {
arg1 = arg1 || 'default value';
}
Note that the default value will be established if arg1 contains any value forgeries, for example null
, undefined
, 0
, false
, NaN
or zero-length string ""
.
Also in JavaScript functions you have an object arguments
, it is an array type object containing the arguments passed to the function, so you can even declare a function with no input arguments, and when you call it, you can pass it:
function whatever() {
var arg1 = arguments[0];
}
whatever('foo');
Edit: To set a default value only if it is indeed undefined, like @bobbymcr , you can do something like this:
function whatever(arg1) {
arg1 = arg1 === undefined ? 'default value' : arg1;
}
source to share
I don't think you can do it directly, but there are ways to achieve it. Since JavaScript allows you to omit parameters from a function call, you can check if the parameter is undefined and give it a default value if so:
function DoSomething(x, y, z)
{
// set default values...
if (typeof x == "undefined")
{
x = 5;
}
if (typeof y == "undefined")
{
y = "Hi";
}
if (typeof z == "undefined")
{
z = 3.14;
}
// ...
}
You can try calling it in the following ways to see what defaults are obtained when the parameter is missing:
DoSomething();
DoSomething(4);
DoSomething(4, "X");
DoSomething(4, "X", 7.77);
source to share