Thursday, September 26, 2013

Difference between == and === in javascript

In almost every programming language the easiest way for comparison is "==". But in javascript there is "===" also available. If you ask anyone what is the difference between == and === is, they will say the same thing, that is === also does the type checking. Well this is absolutely correct, but still the doubt is, how does it work?
Here are few examples -
0 == false -- > true
0 === false -- > false

1 == true --> true
1 === true --> false

2 == true --> false

In order to understand the behavior of == and ===, we need to know few internal methods of javascripts.

ToPrimitive -
Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object.

[[DefaultValue]] - get the output of "toString" or "valueOf" method on the object. If both method not available, then throw exception.

ToNumber -
Argument TypeResult
UndefinedNaN
Null0
Booleantrue - > 1, false - 0
NumberNo change
Stringif it is number as string, then return the number, else NaN
ObjectApply ToPrimitive, then apply ToNumber and get the output
Lets try to understand == first.
Example -> x== y
If the typeOf x and y are same, then there is no confusion, because its normal comparison, but the trick comes when the types are different.
Key Concept - Javascript internally converts x and y both into Numbers, if the Types are different and then do the comparison.
Lets try to practice it by example -
Variable TypeToNumberExample
String
Numeric number in string -> corresponding number
Nan, for everything else
'5' == 5 -> true
'a' == 2 -> false
ObjectApply toprimitive first, and then use above mentioned conversions for comparison
new String('1') == 1 -> true
new Boolean(false) == 0 -> true
NumberNo change
1==2 -> false
3==3 -> true
Boolean
true - > 1
false -> 0
true == 1 -> true ; false == 0 -> true
true == 3 -> false ; false == 1 -> false

In case of x and y being null or undefined, they are compared with following rules -
null == undefined -> true
 
In case of ===, the very first check javascript does is, to check the types of both x and y. Both are of different types then return false, else go ahead with further comparison.

No comments:

Post a Comment