How do you check if a value is an Object in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Do the Java Integer and Double objects have unnece
- Keeping track of variable instances
Return Types
typeof JavaScript constructors and objects (including
null
) returns"object"
Checking on Their constructors
Checking on their
constructor
property returns function with their names.Introducing Function.name
Function.name
returns a readonly name of a function or"anonymous"
for closures.Final code
Ready to use functions for checking
Explanation
In Javascript,
null
,Object
,Array
,Date
andfunction
s are all objects. Although,null
is bit contrived. So, it's better to check for thenull
first, to detect it's not null.Checking for
typeof o === 'object'
guarantees thato
is an object. Without this check,Object.prototype.toString
would be meaningless, since it would return object for everthing, even forundefined
andnull
! For example:toString(undefined)
returns[object Undefined]
!After
typeof o === 'object'
check, toString.call(o) is a great method to check whethero
is an object, a derived object likeArray
,Date
or afunction
.In
isDerivedObject
function, it checks for theo
is a function. Because, function also an object, that's why it's there. If it didn't do that, function will return as false. Example:isDerivedObject(function() {})
would returnfalse
, however now it returnstrue
.One can always change the definition of what is an object. So, one can change these functions accordingly.
Tests
use
typeof(my_obj)
will tells which type of variable it is.if it is object will show 'object'
simple JS function,
Eg:
I was asked to provide more details. Most clean and understandable way of checking if our variable is an object is
typeof myVar
. It returns a string with a type (e.g."object"
,"undefined"
).Unfortunately either Array and null also have a type
object
. To take only real objects there is a need to check inheritance chain usinginstanceof
operator. It will eliminate null, but Array has Object in inheritance chain.So the solution is:
If you are already using AngularJS then it has a built in method which will check if its an object (without accepting null).
I'm fond of simply:
If the item is a JS object, and it's not a JS array, and it's not
null
…if all three prove true, returntrue
. If any of the three conditions fails, the&&
test will short-circuit andfalse
will be returned. Thenull
test can be omitted if desired (depending on how you usenull
).DOCS:
http://devdocs.io/javascript/operators/typeof
http://devdocs.io/javascript/global_objects/object
http://devdocs.io/javascript/global_objects/array/isarray
http://devdocs.io/javascript/global_objects/null