JS: Determine Type of Object
How to determine the “type of an object”?
That is, how to find out if a object is function, array, date, regex, etc?
Check If Object is Array
Array.isArray(obj) → returns true for true array.
[see JS: Array-Like Object]
Check If Object is Function
typeof obj === "function"
Other
The most reliable and generic way to determine the type of object is this:
Object.prototype.toString.call ( obj )
The obj can be any value, such as 3.
The result is one of the following:
"[object Undefined]""[object Null]""[object Array]""[object String]""[object Arguments]""[object Function]""[object Error]""[object Boolean]""[object Number]""[object Date]""[object RegExp]""[object Object]""[object JSON]""[object Set]""[object Map]""[object GeneratorFunction]""[object Generator]"
(there are more, such as WeakMap, WeakSet, Proxy, Promise, etc)
[see JS: Object.prototype.toString]
WARNING: If a obj is a object type, and has a symbol key property Symbol.toStringTag, either own property or inherited, and if its value is a string, let's say tag, then
the result of
Object.prototype.toString.call ( obj )
is the string:
"[object tag]"
[see JS: Symbol Tutorial]
For detail, see JS: Object.prototype.toString
How Does it Work
Object.prototype.toString.call(obj) is using the method Object.prototype.toString on the object obj.
[see JS: Function Call, Apply, Bind]
We don't want to do obj.toString() because object may have its own toString property therefore overrides the Object.prototype.toString.
[see JS: Object.prototype.toString]
JS Types Topic
Object and Inheritance Topic
- JS: Object Overview
- JS: Object Type
- JS: Determine Type of Object
- JS: Object Literal Expression
- JS: Prototype and Inheritance
- JS: Create Object
- JS: Create Object with Parent X
- JS: Get/Set Prototype
- JS: Prevent Adding Property
- JS: Clone, Deep Copy Object/Array
- JS: Test Equality of Objects
- JS: Object Object
- JS: Object.prototype
If you have a question, put $5 at patreon and message me.