Can you declare the arguments of an optional function in Javascript?

How can you in php

<?php
function whatever($var='') {

}
?>

      

can you do it in javascript?

+2


source to share


4 answers


In javascript, you can call a function regardless of parameters.

In other words, it is perfectly legal to declare a function like this:

 function func(par1, par3) {

   //do something
  }

      



and call it like this:

 func();

      

+3


source


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;
}

      

+12


source


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);

      

+2


source


In JS, no arguments are required by default. To implement $ arg = '' you can use

function whatever(vars) {  
   vars = vars || 'default';  
   /* your code */    
}

      

0


source







All Articles