The good:
'hello'.toString() // "hello"
let obj = {}
obj.toString() // "[object Object]"
The bad:
undefined.toString() // throws TypeError
null.toString() // throws TypeError
Are there any other types that will throw on the .toString()
method?
The good:
'hello'.toString() // "hello"
let obj = {}
obj.toString() // "[object Object]"
The bad:
undefined.toString() // throws TypeError
null.toString() // throws TypeError
Are there any other types that will throw on the .toString()
method?
-
4
toString
is defined onObject
, so any type other than undefined and null, which of course do not support any methods at all. – user663031 Commented Aug 15, 2017 at 5:13 -
1
It's worth noting that this works with numeric literals as well, but due to the fact that the period serves double duty as decimal separator and member access operator, you do have to be aware of the syntax.
1.toString()
produces a syntax error, but1..toString()
produces"1"
. – p.s.w.g Commented Aug 15, 2017 at 5:20 - Not all of them do. – Bergi Commented Aug 15, 2017 at 5:29
4 Answers
Reset to default 4From docs of toString()
Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object.
If the variable type is not object, it's going to throw.
So your best bet is you can check test instanceof Object
before calling.
And it is worth mentioning that your code works with 1.8.5 version
var toString = Object.prototype.toString;
toString.call(undefined) // gives [object Undefined]
toString.call(null) // gives [object Null]
Note: Starting in JavaScript 1.8.5 toString() called on null returns [object Null], and undefined returns [object Undefined], as defined in the 5th Edition of ECMAScript and a subsequent Errata. See Using_toString()_to_detect_object_class.
every obj that inherited from Object has to string method.
Starting from javascript Starting in JavaScript 1.8.5 toString() called on null returns [object Null], and undefined returns [objectUndefined].
You can read more about it at this link: You can read more about it at this link
toString
is defined on Object, so any type other than undefined and null will inherit toString
.
Calling toString()
on objects without this method in prototype chain will cause an error. For example:
let a = Object.create(null);
a.toString() //TypeError