Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a variable passed on to a function as null in JavaScript

Tags:

javascript

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?

like image 904
Aerodynamika Avatar asked Mar 15 '14 16:03

Aerodynamika


2 Answers

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
like image 53
Ja͢ck Avatar answered Sep 21 '22 20:09

Ja͢ck


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
like image 26
Rahul Bhanushali Avatar answered Sep 19 '22 20:09

Rahul Bhanushali