In PHP, I have functions set variables to null if the parameter is not passed. For example:
Function call:
myExample(8);
Function definition:
function myExample($var1, $var2 = null);
Expected result:
$var 1 = 8;
$var 2 = null;
Does similar syntax exist in JavaScript? I tried doing it straight up and it didn't work.
In short, no. You can't assign a default value in the function declaration.
But:
function myExample($var1, $var2) {
}
myExample(1);
Will cause $var2 to be undefined inside the function.
In javascript you can pass any number of arguments you want to a function withouth needs to declare them. you can access them with the variable arguments which is kind like an array(it has a length property but in reality is an object)
you can do:
function yourfunction (var1){
var var2 = null;
if (arguments.length>1){
var2 = arguments[1];
}
}
this is quite like what you do in php, because if you don't pass a second argument, var2 is null, otherwise it is equal to the second argument
look here for full reference
EDIT a tipical example is the a function that sums all of his arguments, regardless of the number of them. I found it in several book on javascript. If you want to read more some good boks are: object oriented javascript and javascript patterns both by stoyan stefanov and the usual Javascript: the good parts
function sumValues() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
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