danday74
danday74

Reputation: 57036

In JavaScript, which types support toString()?

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?

Upvotes: 4

Views: 1021

Answers (4)

Ivan Minakov
Ivan Minakov

Reputation: 1442

Calling toString() on objects without this method in prototype chain will cause an error. For example:

let a = Object.create(null); 
a.toString() //TypeError

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

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.

Upvotes: 4

matisa
matisa

Reputation: 529

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

Upvotes: 3

sabrehagen
sabrehagen

Reputation: 1637

toString is defined on Object, so any type other than undefined and null will inherit toString.

Upvotes: 1

Related Questions