Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this PHP syntax exist in JavaScript? function(var = null)

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.

like image 305
dcoffey3296 Avatar asked May 16 '26 23:05

dcoffey3296


2 Answers

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.

like image 69
Quentin Avatar answered May 19 '26 12:05

Quentin


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;
  }
like image 32
Nicola Peluchetti Avatar answered May 19 '26 12:05

Nicola Peluchetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!