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?)

2 Answers

4
Quentin On Best Solutions

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.

-1
Charlie H On

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.