1). Why does 1.toString()
fail?
The JavaScript parser only uses a 1 character lookahead and can't determine if that's 1.0
or 1.toString()
. You can use 1..toString()
to get around that.
2). Will the following function return me a string representation of every possible JavaScript object, value or literal? Function: function str(a) {return a.toString()}
Any literal will be converted to a temporary object in order to have its toString()
called. If the object has its own toString()
defined, it will be called. Otherwise, it will use Object.prototype.toString()
(having gone up the prototype chain) for almost all cases (the other case is an object with a null
prototype).
3). Is there any other alternative to the function str
I have written in the previous point?
Yes. You can invoke the toString()
implicitly by concatenating an empty string, e.g. 1 + ""
. You can also use the String
constructor, e.g. String(value)
(thanks T.J. Crowder). The advantages of these other ones is no exception will be thrown if you attempt to call toString()
on null
or undefined
.
However, these tricks will convert null
and undefined
to their string equivalents (almost never what you want). One dirty trick is to put the value in a literal array, e.g. [value]
and then call toString()
on it. This will actually invoke join(",")
, but seeing as it only has one member, the comma will never become part of the string.
The real power of doing this is that null
and undefined
will just become an empty string. If that's OK for your program, then it can be useful. Keep in mind to comment this solution as it's not immediately obvious what this code is doing. Alternatively, check value == null
which will detect null
and undefined
and handle it appropriately.
However, if you're wanting a string in order to classify a value, you can get the type's [[Class]]
like so...
var getInternalClass = function(value) {
return Object.prototype.toString.call(value).slice(8, -1);
};
This will invoke the Object
's toString()
and set the ThisBinding
to the value provided as the argument. This is the only way to expose an object's internal [[Class]]
. The advantage of this (over typeof
, for example) is that primitives and objects will always return the same value (with the primitives being converted to temporary objects, boxed by the call()
context in non-strict mode).