Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it a bad idea to allow these in JavaScript == , != , ++ , --

I was checking out JSLint, and some of the rules piqued my interest. Particularly this:

Disallow == and !=

Disallow ++ and --

Why is it a bad idea to disallow these? I understand the first part, basically it wants me to do === instead of ==. I don't understand why though. I understand the difference between the two, I just want to know why is it bad practice. Some times I really want to do == for example so that it would evaluate true for undefined == null

The second one, well I don't understand at all. Does it want me to do myInt += 1 instead of myInt++ ?

Thanks!

like image 667
7wp Avatar asked Jul 28 '10 21:07

7wp


1 Answers

I don't agree too much with those rules, instead of discouraging the use of ==, I would recommend to learn about type coercion.

The primary reason about why Crockford wants to avoid == is that the comparison rules depending on the types of the operands can make this operator non-transitive, for example, if:

A == B AND
B == C

Doesn't guarantees that:

A == C

A real example:

'0' == 0; // true
 0 == '';   // true
'0' == ''; // false

The strict === operator is not really necessary when you compare values of the same type, for example:

 if (typeof foo == "function") { }

We compare the result of the typeof operator, which is always a string, with a string literal...

Another example, when you compare something against null, == also compares against undefined, for example:

if (something == null) {}

VS

if (something === null || typeof something === "undefined") {}

The above two conditions are at the end equivalent, but the first one much more readable, of course if you know about type coercion and how == behaves.

Learning how the == operator works, will help you to wisely decide which to use.

Recommended articles:

  • ECMAScript. Equality operators (Great tips to remember how == works)
  • typeof, == and ===
like image 191
Christian C. Salvadó Avatar answered Oct 13 '22 19:10

Christian C. Salvadó