Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, which types support toString()?

Tags:

javascript

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?

like image 223
danday74 Avatar asked Jan 04 '23 14:01

danday74


1 Answers

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.

like image 158
Suresh Atta Avatar answered Jan 15 '23 23:01

Suresh Atta