pimvdb
pimvdb

Reputation: 154868

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

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

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 what advantages === has over == here. Basically, .length returns a Number, and 1 is a Number as well. You can be 100% sure, so === is just a redundant extra token. Also, checking for the type whilst you know the types will always be the same has no performance advantage either.

So what's actually the reason behind using === here?

Upvotes: 6

Views: 781

Answers (3)

Piskvor left the building
Piskvor left the building

Reputation: 92772

Well, === is supposed to be infinitesimally faster, as it can fail faster (on type mismatch), but that's deep inside the "pointless microoptimizations" territory.

Realistically, I'd advise for ===, even if you are 105% sure - I've been tripped up by my assumptions too many times ("yes, I am positive they are the ... same ... uh ..."). Unless there's a good reason to turn them off, it is better to keep sanity checks enabled in code than trust to do them in your mind.

Upvotes: 1

Andrea
Andrea

Reputation: 20493

The only reason is that you don't have to think whether the comparison you are doing will involve coercion or not. If you stick to using ===, you just have one thing less to worry about.

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

Upvotes: 4

Adam Hopkinson
Adam Hopkinson

Reputation: 28795

It's not strictly required, as you know the length function is well-tested. But what if length was a bit buggy, and there was a chance it could return false?

In this situation, both 0 and false would be evaluated as false using the == comparison. To test for false (when there is also the chance of 0 being returned), you need to also check the data type, which is where === comes in.

Upvotes: 1

Related Questions