JavaScript has Strict Equality a.k.a
===
comparison and Abstract Equality a.k.a==
comparison. It is the latter's lack of understanding which might cause bugs.
Rules
These are the rules which come into effect while resolving the abstract equality -
- If
x=null
andy=undefined
, returntrue
; - If
x=undefined
andy=null
, returntrue
; - If
Type(x)
is same asType(y)
then perform strict equality comparison. - If
Type(x)=Number
andType(y)=String
, return result ofx==ToNumber(y)
- If
Type(x)=String
andType(y)=Number
, return result ofToNumber(x)==y
- If
Type(x)=Boolean
, return result ofToNumber(x)==y
- If
Type(y)=Boolean
, return result ofx==ToNumber(y)
- If
Type(x)
is eitherString, Number or Symbol
&Type(y)
isObject
, then return result ofx==ToPrimitive(y)
- If
Type(y)
is eitherString, Number or Symbol
&Type(x)
isObject
, then return result ofToPrimitive(x)==y
Type, ToNumber, ToBoolean are all abstract operations, they are implemented by the JS engine
ToPrimitive, ValueOf, ToString
8th and 9th cases are quite interesting. It involves the conversion of a non-primitive value to a primitive one.
According to the spec, the ToPrimitive
method accepts two arguments - Input and optional PreferredType hint (it could be either string
, number
or default
).
An object
utilizes the following two methods for conversion if the ToPrimitive
is not available for the object
-
valueOf
- takes precedence in case ofnumber
hint i.e during numerical comparisons, followed by a call totoString
, if the former does not yield a primitive valuetoString
- takes precedence in case ofstring
hint, followed by a call tovalueOf
, if the former does not yield a primitive value
For the default
hint case, it's considered as number
unless the object
is of Date
type.
Enough talking, let's see code in action for the above statements
Implementing ToPrimitive
Symbol.toPrimitive
is the way to implement an object
's toPrimitive
operation. If this method does not return a primitive, then an error is thrown. The snippet below shows how one could implement any custom logic for object coercion.
Reference:
That's all people!
Top comments (0)