Short answer
The safest bet is undefined
, and should work almost ubiquitously. Ultimately, though, you cannot trick the function being called into thinking you truly omitted a parameter.
If you find yourself leaning towards using null
just because it's shorter, consider declaring a variable named _
as a nice shorthand for undefined
:
(function() { // First line of every script file
"use strict";
var _ = undefined; // For shorthand
// ...
aFunction(a, _, c);
// ...
})(); // Last line of every script
Details
First, know that:
typeof undefined
evaluates to "undefined"
typeof null
evaluates to "object"
So suppose a function takes an argument that it expects to be of type "number"
. If you provide null
as a value, you're giving it an "object"
. The semantics are off.1
As developers continue to write increasingly robust javascript code, there's an increasing chance that the functions you call explicitly check a parameter's value for undefined
as opposed to the classic if (aParam) {...}
. You'll be on shaky ground if you continue to use null
interchangeably with undefined
just because they both happen to coerce to false
.
Be aware, though, that it is in fact possible for a function to tell if a parameter was actually omitted (versus being set to undefined
):
f(undefined); // Second param omitted
function f(a, b) {
// Both a and b will evaluate to undefined when used in an expression
console.log(a); // undefined
console.log(b); // undefined
// But...
console.log("0" in arguments); // true
console.log("1" in arguments); // false
}
Footnotes
- While
undefined
also isn't of type "number"
, it's whole job is to be a type that isn't really a type. That's why it's the value assumed by uninitialized variables, and the default return value for functions.
undefined
?) but it sure looks best for "skipping optional parameters". – Premonish