Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 819
pimvdb Avatar asked Mar 04 '11 11:03

pimvdb


People also ask

Should you always use === JavaScript?

The advice given to JavaScript beginners is to completely forget about == and to always use ===. It turns out that that rule is universally true.

Why we use === in TypeScript?

Why? Because Typescript ensures that both operands of comparison operator(s) have the same type. When both operands have the same type == and === behave identically.

Why would you use === instead of ==?

Use === if you want to compare couple of things in JavaScript, it's called strict equality, it means this will return true if only both type and value are the same, so there wouldn't be any unwanted type correction for you, if you using == , you basically don't care about the type and in many cases you could face ...

Should I use == or === in JavaScript?

== in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values. Checks the equality of two operands without considering their type. Compares equality of two operands with their types.


1 Answers

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.

like image 97
Andrea Avatar answered Oct 26 '22 01:10

Andrea