JS: Object .prototype .toString
Object.prototype.toString()-
The input of this function is the value of this-binding.
Input can be any type, including Primitive Value.
Return a string indicating the type of the object.
console.assert( Reflect.apply( Object.prototype.toString, [3, 4], [], ) === "[object Array]", ); console.assert( Reflect.apply( Object.prototype.toString, {}, [], ) === "[object Object]", ); console.assert( Reflect.apply( Object.prototype.toString, /x/, [], ) === "[object RegExp]", ); console.assert( Reflect.apply( Object.prototype.toString, new Date(), [], ) === "[object Date]", ); If input is a object, and has a Symbol key property
Symbol.toStringTag, either own property or inherited, and its value is a string, let's say the value is tag, then the result is"[object tag]"/* Example of object that has property key Symbol.toStringTag and value is a string. */ let jj = {}; jj[Symbol.toStringTag] = "xyz"; console.log( Reflect.apply(Object.prototype.toString, jj, []) === "[object xyz]", );
Common use-case
Usually used like these:
Object.prototype.toString.call(obj)Reflect.apply( Object.prototype.toString , obj, [] )
Often used to determine the “type of object”.
For example, {} is a data object, but /abc/ is regexp object.
Standard objects
here's a list of all possible results for standard objects:
// objects on the left have the types of right-hand-side. // right-hand-side is from Object.prototype.toString [ [new Object(), "[object Object]"], [new Array(), "[object Array]"], [new RegExp(), "[object RegExp]"], [new Date(), "[object Date]"], [new Function(), "[object Function]"], [new Set(), "[object Set]"], [new Map(), "[object Map]"], [new Error(), "[object Error]"], [new WeakMap(), "[object WeakMap]"], [new WeakSet(), "[object WeakSet]"], [function* () {}, "[object GeneratorFunction]"], [(function* () {})(), "[object Generator]"], [Symbol(), "[object Symbol]"], [JSON, "[object JSON]"], [Math, "[object Math]"], [new Promise(() => {}), "[object Promise]"], [(x) => 3, "[object Function]"], ].forEach(([xval, xtypestr]) => { console.assert(Reflect.apply(Object.prototype.toString, xval, []) === xtypestr); }); // primitives [ [1, "[object Number]"], [Infinity, "[object Number]"], [NaN, "[object Number]"], ["", "[object String]"], [true, "[object Boolean]"], [undefined, "[object Undefined]"], [null, "[object Null]"], ] .forEach(([xval, xtypestr]) => { console.assert(Reflect.apply(Object.prototype.toString, xval, []) === xtypestr); }); // the arguments object inside function (function ff() { console.assert(Reflect.apply(Object.prototype.toString, arguments, []) === "[object Arguments]"); })();