Why In JavaScript Are Some Things Not Equal?

I just finished watching a Kyle Simpson video on type coercion which I thought was very insightful (references are below). Here are some of my notes.

NEVER == false or == true

Problems with using == is the following:

“0” == false;   // => true!
0 == false;     // => true!
“” == false;    // => true!
[] == false;    // => true!
“” == 0;        // => true!
“” == [];       // => true!
0 == [];        // => true!

If you never use the double equal comparative sign for == false or == true then out of the 7 problems above, 4 go away.

[] == ![];      // => true

Why does this happen?

The negation of an empty array is false.

To avoid coercion problems use the following rules (ask yourself when doing a comparison if any of the values being compared could EVER be any of the following):

  1. Can either value be true or false? If so, use triple equals.
  2. Can either value be [], “” or 0? If so, use triple equals.

Let’s check the following examples which aren’t bad:

42 == “43”;             // => false
“foo” == 42;            // => false
“true” == true;         // => false
42 == “42”;             // => true
“foo” == [ “foo” ];     // => true

This is what we think:

== checks value
=== checks value and type

However the spec states:

== allows coercion
=== disallows coercion

See Kyle’s Coercion Grid

var foo = “3”;
// using triple equals to test the variable - note that it has to do 2 checks!
if ( foo === 3 || foo === “3” ) {
    alert( “Yay!”);
}
// using double equals to test the variable
if ( foo == 3 ) {
    alert( “Yay!” );
}

Which is easier to read?

Another test:

var foo; // note that it's `undefined`
if ( foo == null ) {
    alert( “Yay!” );
}

foo = null;
if ( foo == null ) {
    alert( “Yay!” );
}

foo = false;
if ( foo == null ) {
    alert( “Should never come in here!” );
}

As null and undefined are coerced to be the same we can use these comparisons.