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?
When no argument is passed,
bisundefined, notnull. So, the proper way to test for the existence of the argumentbis this:!==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’sundefinedor not.