Checking for passed parameters using null - JavaScript
function, javascript, parameters, typeof
Solution
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.
Problem
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?