You Don’t Know Java Script- Up and Going Part 1

Comparison Operators

if I ask you what is result of the following ?

var a = [‘a’ ,’b’, ‘c’];
var b = [‘a’ ,’b’,’c’];
a == b

most probably you would say true right ? But that’s not the case here, the answer is false
let us examine why

when you are using == or === operators for comparing non primitive types, i.e functions or objects including arrays, they will simply check whether the references match, not anything about underlying values.

for example in case of arrays , while comparing , all array values are by default coerced in to strings by joining all values with commas( , ) in between.  consider below example now

var a = [1 ,2 ,3];
var b = [1 ,2 , 3];
var c = “1,2,3”;
a == c;  // will return true

Inequality and Coercion

var a = 41;
var b = “42”;
var c = “43”;
a < b;   // true;
a < c;   // true;

In case of above inequality comparison,

  • when comparing two string values , the comparison is made lexicographic-ally i.e the case with a < b
  • where  as, if any one of the both is not a string then both values are coerced with numbers.

So what will be the result of comparing a Number and a String if both are coerced in to numbers?

var a = 42;
var b = “foo”;
a > b;  //false
a < b;  // false
a == b;  //false

So now what do you think coercion of  “foo” will be ?
its “Invalid Number Value” NAN

And the specification says NAN is neither greater nor less than any other value hence the result is false for the above.

 

 

 

 

 

 

 

Advertisements