0

A friend said I should use ! (obj == null), because it's better than obj != null, but he didn't remember why to do this.

Is there any reason for using ! (obj == null)?

Is there any difference? I mean, both should return true when the obj is not null and neither undefined, is that right or not? (I am a little confused)

And when the answer is both result to the same, then I would like to know, is that right for all JavaScript versions? (I mean, both work on all browsers or not?)

Top-Master
  • 2,934
  • 1
  • 17
  • 34

2 Answers2

4

Is there any reason for using ! (obj == null)?

Some people may find it easier (or harder) to read.

is there any change, I mean, both should return true when the obj is not null and neither undefined, is that right or not? (I am a little confused)

No. They mean exactly the same thing.

And when the answer is both result to the same, then I would like to know, is that right for all java-script versions? (I mean, both work on all browsers or not?)

Yes.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • thanks, I also found some other useful posts, like [difference between == and ===](https://stackoverflow.com/questions/5101948/javascript-checking-for-null-vs-undefined-and-difference-between-and/5101991) which I would like to link here... – Top-Master May 01 '19 at 10:19
-1

The ! (obj == null) will have to perform a comparison operation as well as a boolean operation. So, it is bit slower.

On the other hand, obj != null is a single comparison.

The fastest is obj !== null which doesn't have to do type coercion.

However, the change of performance of above three cases in average programs are insignificant.

Charlie
  • 18,636
  • 7
  • 49
  • 75
  • 1
    This answer is therefore also *insignificant* ... I also doubt that this statement is actually true (that there is actually any difference in the JITed code). – Jonas Wilms May 01 '19 at 08:53
  • "This answer is therefore also insignificant" - nice logic ;). // I also doubt that this statement is actually true - Go ahead and do a simple performance test. – Charlie May 01 '19 at 09:06