Like you can in php
<?php
function whatever($var='') {
}
?>
can you do that in javascript?
Like you can in php
<?php
function whatever($var='') {
}
?>
can you do that in javascript?
In javascript you can call a function regardless of parameters.
In other words it's perfectly legal to declare a function like this:
function func(par1, par3) {
//do something
}
and call it like this:
func();
If you want to set a 'default' value to your arguments, you can do something like this:
function whatever(arg1) {
arg1 = arg1 || 'default value';
}
Keep in mind that the 'default value' will be set if arg1 contains any falsy value, like null
, undefined
, 0
, false
, NaN
or a zero-length string ""
.
Also in JavaScript functions you have the arguments
object, it's an array-like object that contains the arguments passed to a function, therefore you can even declare a function without input arguments, and when you call it, you can pass some to it:
function whatever() {
var arg1 = arguments[0];
}
whatever('foo');
Edit: For setting a default value only if it is truly undefined, as @bobbymcr comments, you could do something like this also:
function whatever(arg1) {
arg1 = arg1 === undefined ? 'default value' : arg1;
}
In JS by default arguments aren't required. For $arg = '' implementation you can use
function whatever(vars) {
vars = vars || 'default';
/* your code */
}
I don't think you can do this directly, but there are ways to achieve this. Since JavaScript lets you omit parameters from a function call, you can check if a 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 the default values get assigned when the parameter is missing:
DoSomething();
DoSomething(4);
DoSomething(4, "X");
DoSomething(4, "X", 7.77);