Like you can in php
<?php
function whatever($var='') {
}
?>
can you do that in javascript?
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 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With