Take an example function here:
function a(b){
console.log(b != null ? 1 : 2);
}
That code works fine, by printing 1 if you pass a parameter, and 2 if you don't.
However, JSLint gives me a warning, telling me to instead use strict equalities, i.e !==
. Regardless of whether a parameter is passed or not, the function will print 1 when using !==
.
So my question is, what is the best way to check whether a parameter has been passed? I do not want to use arguments.length
, or in fact use the arguments
object at all.
I tried using this:
function a(b){
console.log(typeof(b) !== "undefined" ? 1 : 2);
}
^ that seemed to work, but is it the best method?
To check if a parameter is provided to a function, use the strict inequality (! ==) operator to compare the parameter to undefined , e.g. if (param !== undefined) . If the comparison returns true , then the parameter was provided to the function.
You can check for null with the typeof() operator in JavaScript. Curiously, if you check with typeof() , a null variable will return object .
In JavaScript, parameters of functions default to undefined, but its fine to pass null as a paramter in JS functions if need be.
As shown above, null is only loosely equal to itself and undefined , not to the other falsy values shown. This can be useful for checking for the absence of value — null and undefined both indicate an absence of value, thus they are loosely equal (they have the same value even though they are different types).
When no argument is passed, b
is undefined
, not null
. So, the proper way to test for the existence of the argument b
is this:
function a(b){
console.log(b !== undefined ? 1 : 2);
}
!==
is recommended because null and undefined can be coerced to be equal if you use ==
or !=
, but using !==
or ===
will not do type coercion so you can strictly tell if it's undefined
or not.
You can use the falsy nature of undefined
(a parameter, which was not passed is in fact undefined
, not null
) and just write:
(!b)?1:2
However this will also be true for 0
, null
and ""
(falsy values).
If you want to write it the bulletproof way, you can go:
typeof(b) === "undefined"
// or thanks to the write protection for undefined in html5
b === undefined
Update: thanks to EcmaScript 2015, we now can use default parameters:
function a(b = 1){
console.log(b);
}
If a parameter is undefined - either ommited or explicitely handed over (here you should use null
instead) - the default value will be used, all other values remain unchanged (also falsy ones). Demonstration
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