Wednesday 6 August 2014

Equality operators in Javascript - My First googly

Among other concepts of Javascipt where I stumbled this one was a complete bouncer (can't blame a citizen of Cricket crazy country).

To grasp the concept of
Equal (==)
Not-Equal(!=)
Identically Equal(===)
Not Identically Equal(!==)

lets first talk about type coercion.

What ECMAScript ( Javascript) does is that it tries to align the type of operands before comparison , this is simply type coercion. This simple but powerful concept is cause of some good quirks in Javascript.

Equal & Not Equal

Equal and Not Equal performs the type coercion, meaning that before performing the comparison Javascript attempts to convert the type of operands to be same

Following rules are applied for conversion:
  • Boolean are converted to numeric
         false == 0 //true
         true ==1 //true
  • When comparing string with numeric, string is converted to numeric
         "1" == 1 //true
  • Comparing object with primitive, valueof is called on the object to get the primitive value of the object and that is used for comparison.
  • Value of null and undefined are equal. (yes null== undefined is true)
  • Value of null and undefined is not converted to anything else.
        null ==5// false
  • Special treatment is given to NaN. If one of the operands is NaN equality operator returns false and not equality returns true. 
  • NaN is not equal to NaN.
  • If both operands are object then if they are pointing to same object then only they are equal else not equal.
         var a = new Object();
         a.val =5;          var b = new Object();          b.val=5;          console.log(a==b); // false

         var a = new Object();
         a.val =5;          var b = a;          console.log(a==b); // true



Identically Equal and Not Identically Equal

No type coercion is involved in these thus not issues due to type conversion. Thus
       "1" === 1 // false
        null === undefined //true

Word of advice, if not sure and to maintain the consistency always use Identically Equal and Not Identically Equal.

No comments:

Post a Comment