JavaScript: Determine Type of Object
How to find out if a object is function, array, date, regex, etc?
Check If Object is Array
Array.isArray(obj)
-
Return
true
for true array. [see 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:
Reflect.apply( Object.prototype.toString , obj, [] )
or
Object.prototype.toString.call(obj)
The obj can be any value, object type or not, such as 3
.
const x = /123/; console.log( Object.prototype.toString.call ( x ) === "[object RegExp]" ); console.log( Reflect.apply ( Object.prototype.toString , x, [] ) === "[object RegExp]" );
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]"
etc.
See: 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 Symbol Tutorial]
For detail, see Object.prototype.toString
How Does it Work
Reflect.apply( Object.prototype.toString , obj, [] )
Applies the function
Object.prototype.toString
and passing
obj as thisBinding,
with no argument.
Object.prototype.toString.call(obj)
does the same.
[see 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 Object.prototype.toString]