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?
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With