Javascript has lot’s of “tricks” around types and type conversions so I’m wondering if these 2 methods are the same or if there is some corner case that makes them different?
Javascript has lot’s of tricks around types and type conversions so I’m wondering if
Share
They are not completely the same, and actually, the String constructor called as a function (your first example), will at the end, call the
toStringmethod of the object passed, for example:On the other hand, if an identifier refers to
nullorundefined, you can’t use thetoStringmethod, it will give you aTypeErrorexception:The
Stringconstructor called as a function would be roughly equivalent to:The type conversion rules from Object-to-Primitive are detailed described on the specification, the
[[DefaultValue]]internal operation.Briefly summarized, when converting from Object-to-String, the following steps are taken:
toStringmethod.resultis a primitive, returnresult, else go to Step 2.valueOfmethod.resultis a primitive, returnresult, else go to Step 3.TypeError.Given the above rules, we can make an example of the semantics involved:
If you want to know more about this mechanism I would recommend looking at the
ToPrimitiveand theToStringinternal operations.I also recommend reading this article: