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?

1
  • 3
    Well if it's not passed its value will be undefined. Do you need specifically a null value? Commented Mar 15, 2014 at 16:03

6 Answers 6

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
Sign up to request clarification or add additional context in comments.

Comments

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'?

4 Comments

technically there is nothing wrong with this answer, but what happens when two params are passed, or three, or four...
@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.
@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.
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.
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

1 Comment

This isn't functionally equivalent, though. typeof x === 'undefined' is much more specific, as this only checks for falsiness; 0, '' and others are also falsey.
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.

5 Comments

This only works for variables that evaluate to "true". something(0,false) would not work as expected.
OP asked 'How to set that if there is no variable passed ...'
True. But still that would not work. If "false" or 0 is passed, then variable || null evaluates to null.
If false or 0 is passed, something is passed, albeit something evaluating to null.
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.
1

Test the value of your variable like this:

function something (variable) {
    variable = (typeof variable !== 'undefined') ? variable : null;
}

1 Comment

Sorry, I didn't notice I wasn't editing my own answer.
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

5 Comments

Thanks, @John - and if I pass something like getProfile('tom', 'smith) – then the function assumes that othervar2 is null? or false? or undefined?
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.
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
This solution will raise false-negatives if singleVariable is a falsy value, but a value you passed on purpose nonetheless.
The || false doesn't affect the behavior of the program; the function would work the same if that line was removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.