Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is not good to use "!= null" to test if argument is passed [duplicate]

Tags:

javascript

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 ?

like image 454
vancewang Avatar asked Jul 16 '13 14:07

vancewang


1 Answers

!= 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:

  1. Nothing was passed for the argument at all.

  2. null was passed.

  3. 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.

like image 91
T.J. Crowder Avatar answered Nov 05 '22 21:11

T.J. Crowder