Why use === when you are sure the types are equal?

It seems that the strict equality operator is strictly adhered to whenever possible - I put my code in JSLint and got the following feedback.

the code:

function log() { console.log(arguments.length == 1 ? arguments[0] : arguments); } 

Feedback from JSLint:

 Problem at line 2 character 34: Expected '===' and instead saw '=='. 

I am curious to know which benefits === exceed == here. Basically, .length returns a Number , and 1 returns Number . You can be 100% sure, therefore === is just an extra extra token. In addition, type checking while you know that types will always be the same also has no performance advantages.

So what really is the reason for using === here?

+6
javascript equality jslint types
source share
3 answers

The only reason is that you donโ€™t need to think whether the comparison you made will include coercion or not. If you stick to using === , you just need to worry about one thing.

Of course, not everyone agrees . This is why you can disable certain checks in JSlint if you are sure what you are doing.

+4
source share

This is not strictly required, since you know that the length function is well tested. But what if length was a bit of a mistake, and there was a chance it could return false ?

In this situation, both 0 and false will be evaluated as false using the comparison == . To check the value false (when there is a chance of a return of 0 ), you also need to check the data type, which includes === .

+1
source share

Well, === supposed to be infinitely faster, since it can come out faster (with type mismatch), but deep down inside the area of โ€‹โ€‹"meaningless microoptimizations".

Actually, I would advise for === , even if you are 105% sure - my assumptions have argued too much ("yes, I'm sure that they ... are the same ... hh ..."). If they have no good reason to disable them, it is better to keep health checks in the code than to trust to do it in their mind.

+1
source share

All Articles