views:

287

answers:

4

Like you can in php

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

}
?>

can you do that in javascript?

+2  A: 

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();
Robban
So is this "yes, you can set a default value", or "no, you cannot set a default value" ?
Zed
I phrased it wrong, what I meant was that can you add parameters without them having to be defined. And the answer is yes, you can. Unlike PHP.
Tom
+8  A: 

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;
}
CMS
let's work together :D
Mushex Antaranian
See my answer for how to set default only if it is truly undefined.
bobbymcr
You forgot falsy `NaN` :)
kangax
@kangax: Oh yes, I missed NaN... adding it now... :)
CMS
A: 

In JS by default arguments aren't required. For $arg = '' implementation you can use

function whatever(vars) {  
   vars = vars || 'default';  
   /* your code */    
}
Mushex Antaranian
+2  A: 

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);
bobbymcr
Just to me I prefer x === undefined; To avoid typeof :)
Mushex Antaranian