8

Suppose I have a function in JavaScript:

function something (variable) {
    console.log(variable);
}

How do I set that if there is no variable passed, then it is null by default?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aerodynamika
  • 7,883
  • 16
  • 78
  • 137
  • 3
    Well if it's not passed its value will be undefined. Do you need specifically a `null` value? – Mitya Mar 15 '14 at 16:03

6 Answers6

7

JavaScript isn't very picky when it comes to the number of required function arguments when you call a function; any arguments that are mentioned in the declaration but not passed will be set to the type undefined.

For example:

function test(foo)
{
    console.log(foo === undefined); // true
}

To set default values there are at least three options:

function test(foo)
{
    console.log(foo || 'default value');
}

The above will output the value of foo if it's truthy, or 'default value' otherwise.

function test(foo)
{
    console.log(foo === undefined ? foo : 'default value');
}

This will output the value of foo if it's not undefined, or 'default value' otherwise.

Lastly, you can count the number of arguments that were passed:

function test(foo)
{
    console.log(arguments.length > 0 ? foo : 'default value');
}

This will output the value of foo (regardless of its type) if an argument was passed.

Further considerations

Although undefined is not writeable since ES5, not all browsers will be so vigilant to enforce this. There are two alternatives you could use if you're worried about this:

foo === void 0;
typeof foo === 'undefined'; // also works for undeclared variables
Community
  • 1
  • 1
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

You can check the size of arguments variable,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments

function something (variable) {
  if(arguments.length===0){console.log("variable is null");}
  else{
    console.log(variable);
  }
}

Also have a look here in order to check if the variable is null,

How to determine if variable is 'undefined' or 'null'?

Community
  • 1
  • 1
melc
  • 11,523
  • 3
  • 36
  • 41
  • technically there is nothing wrong with this answer, but what happens when two params are passed, or three, or four... –  Mar 15 '14 at 18:01
  • @John it is possible to use `arguments` for an arbitrary number of parameters and decide based on the state and position in the `arguments` object, regardless of the name of the variables. can you please elaborate a little more on your thought? maybe i'm missing something you are saying. – melc Mar 15 '14 at 18:42
  • @John For example `arguments[0]` would correspond to `variable1`, `arguments[1]` would correspond to `variable2`, `argument[N-1]` would correspond to `variableN` in order to check their if `null` or something else. Also `argument.length===N-1` would mean that `variableN` has not been passed. – melc Mar 15 '14 at 18:49
  • http://jsfiddle.net/7fJp3/ I didn't realise you could use the arguments in this way.. i thought the arguments had to essentially be a numeric array. –  Mar 15 '14 at 21:10
2

It should be as simple as:

function something (variable) {
    console.log(variable || null);
}

In general you can assign default values to parameters like this:

function something (somevar1, somevar2 /* ... somevarn */) {
    somevar1 = somevar1 || 'somevar1 not present';
    somevar1 = somevar2 || 2;
    somevar3 = somevar3 || {foo: 'bar', foobar: null}
    /* etc. */
}

Or, if you need a defence against 0, false, etc. (and to serve @Ketola), you could cook up something like:

function something (somevar1) {
    somevar1 = ['', 0, false, null, undefined].indexOf(somevar1) > -1
               && null || somevar1;
}

... this || that is known as short circuit evaluation.

Community
  • 1
  • 1
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • This only works for variables that evaluate to "true". `something(0,false)` would not work as expected. – Ketola Mar 15 '14 at 16:18
  • OP asked 'How to set that *if there is no variable passed* ...' – KooiInc Mar 15 '14 at 16:21
  • 2
    True. But still that would not work. If "false" or 0 is passed, then `variable || null` evaluates to null. – Ketola Mar 15 '14 at 16:23
  • If `false` or `0` is passed, *something* is passed, albeit something evaluating to null. – KooiInc Mar 15 '14 at 16:32
  • 3
    OP asked "How to set that if there is no variable passed, then it is `null` by default", so the solution should not set the variable to `null` if variable *is* defined. – Ketola Mar 15 '14 at 16:43
2

All the above will work for sure, but this is the simplest approach and I use this the most.

variable = variable ? variable : undefined; // you can use null as well
Rahul Bhanushali
  • 553
  • 5
  • 14
  • This isn't functionally equivalent, though. `typeof x === 'undefined'` is much more specific, as this only checks for falsiness; `0`, `''` [and others](http://stackoverflow.com/questions/19839952/all-falsey-values-in-javascript-values-where-value-is-true) are also falsey. – yerforkferchips Nov 29 '14 at 15:36
1

Test the value of your variable like this:

function something (variable) {
    variable = (typeof variable !== 'undefined') ? variable : null;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
R3tep
  • 12,512
  • 10
  • 48
  • 75
1

Or a more friendly (IMO) option would be:

function getProfile( singleVariable )
{
    singleVariable = singleVariable || false;
    if (singleVariable) {
        alert('we have a var')
    }
    else {
        alert('nothing opassed');
    }
}
getProfile();
getProfile('tom');

Then when you start passing lots of parameters over, but want the function to be flexible you can do:

function getProfile(params)
{
    params = params || {};

    if (params.username) {
        alert(params.username)
    }
    if (params.id) {
      alert(params.id);
    }
}
getProfile();
getProfile({username:'tom', id: 123654987});

Instead of

function getProfile(singleVariable, otherVar, othervar2)
{
    singleVariable = singleVariable || false;
    otherVar = otherVar|| false;
    otherVar2 = singleVariable2 || false;

    if( singleVariable ){
        alert('we have a var')
    }
    else {
        alert('nothing opassed');
    }
}

getProfile('tom', false, 'smith');

That false is required and is annoying.. passing an abject is far more efficient

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Thanks, @John - and if I pass something like getProfile('tom', 'smith) – then the function assumes that othervar2 is null? or false? or undefined? – Aerodynamika Mar 15 '14 at 17:20
  • undefined. however i really strongly advise against using this method. as your application grows the management of parameters passed in this fashion becomes a nightmare. –  Mar 15 '14 at 17:54
  • in fact any 3rd party pluggin that is half decent will expect an array (object) passed to it. eg: $.ajax({url:'www.blah',type:'GET',success:function(data){alert(data);}}) To add to this, as you are passing effectively an assoc array, the order of the params you pass them in is irrelevant –  Mar 15 '14 at 17:57
  • 1
    This solution will raise false-negatives if `singleVariable` is a falsy value, but a value you passed on purpose nonetheless. – dee-see Mar 15 '14 at 22:23
  • The `|| false` doesn't affect the behavior of the program; the function would work the same if that line was removed. – user2357112 Mar 15 '14 at 23:50