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?
From 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With