From the book Maintainable JavaScript it mentioned :
// Bad: Testing to see if an argument was passed
function doSomething(arg1, arg2, arg3, arg4){
if (arg4 != null){
doSomethingElse();
}
}
but I feel using != null
here is quite effective, it filtered both the case of argument not passed or it is passed as null
any reason why the author suggest it is bad ?
!= null
is false for undefined
, it basically means x !== null && x !== undefined
. !=
does type coercion, and one of the effects of that is that it treats null
and undefined
as equivalent (null == undefined
is true).
So unless you want that, some people recommend not using !=
with null
(or undefined
).
And you're quite right that the code defends against two (well actually three) possibilities:
Nothing was passed for the argument at all.
null
was passed.
undefined
was passed.
But the comment says it's a bad way to test whether an argument was passed, and it is: Because it doesn't catch passing null
or undefined
. (Passing in null
and not passing in anything are different cases.) That doesn't necessarily mean it's a bad way to check the argument for a specific function.
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