How do you check if a value is an Object in JavaScript?
Try using typeof(var) and/or var instanceof something.
EDIT: This answer gives an idea of how to examine variable's properties, but it is not a bulletproof recipe (after all there's no recipe at all!) for checking whether it's an object, far from it. Since people tend to look for something to copy from here without doing any research, I'd highly recommend that they turn to the other, most upvoted (and correct!) answer.
-
147
-
50
-
113@MichaelKrelin-hacker: That's unfortunate since it confuses people. – RightSaidFred Dec 14 '11 at 21:55
-
11@RightSaidFred, I have no explanation for it, but I am absolutely not inclined to add extra brackets in these expressions :) – Michael Krelin - hacker Dec 15 '11 at 6:50
-
86This answer is incorrect.
typeofreturns 'object' for null, which is not an object, andinstanceofdoesn't work for objects created usingObject.create(null). – Nikolai Apr 8 '14 at 21:12
If typeof yourVariable === 'object', it's an object or null. If you want to exclude null, just make it yourVariable !== null && typeof yourVariable === 'object'.
-
79
-
12
-
3
-
6@RightSaidFred Seems that
typeof null == 'object'will not be fixed in ES6. They said:This proposal has been rejected. It was implemented in V8 but it turned out that it broke a lot of existing sites. In the spirit of One JavaScript this is not feasible.– Konstantin Smolyanin Sep 3 '13 at 10:50 -
5@Tresdin The best way is to run
Object.prototype.toString.call(yourVar), being yourVar what you need to inspect. In case of arrays,Object.prototype.toString.call([1,2])returns[object Array]– Jose Rui Santos Feb 25 '16 at 9:48
Let's define "object" in Javascript. According to the MDN docs, every value is either an object or a primitive:
primitive, primitive value
A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined.
What's a primitive?
3'abc'truenullundefined
What's an object (i.e. not a primitive)?
Object.prototype- everything descended from
Object.prototypeFunction.prototypeObjectFunctionfunction C(){}-- user-defined functions
C.prototype-- the prototype property of a user-defined function: this is notCs prototypenew C()-- "new"-ing a user-defined function
MathArray.prototype- arrays
{"a": 1, "b": 2}-- objects created using literal notationnew Number(3)-- wrappers around primitives- ... many other things ...
Object.create(null)- everything descended from an
Object.create(null)
How to check whether a value is an object
instanceof by itself won't work, because it misses two cases:
// oops: isObject(Object.prototype) -> false
// oops: isObject(Object.create(null)) -> false
function isObject(val) {
return val instanceof Object;
}
typeof x === 'object' won't work, because of false positives (null) and false negatives (functions):
// oops: isObject(Object) -> false
function isObject(val) {
return (typeof val === 'object');
}
Object.prototype.toString.call won't work, because of false positives for all of the primitives:
> Object.prototype.toString.call(3)
"[object Number]"
> Object.prototype.toString.call(new Number(3))
"[object Number]"
So I use:
function isObject(val) {
if (val === null) { return false;}
return ( (typeof val === 'function') || (typeof val === 'object') );
}
@Daan's answer also seems to work:
function isObject(obj) {
return obj === Object(obj);
}
because, according to the MDN docs:
The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a type that corresponds to the given value. If the value is an object already, it will return the value.
A third way that seems to work (not sure if it's 100%) is to use Object.getPrototypeOf which throws an exception if its argument isn't an object:
// these 5 examples throw exceptions
Object.getPrototypeOf(null)
Object.getPrototypeOf(undefined)
Object.getPrototypeOf(3)
Object.getPrototypeOf('abc')
Object.getPrototypeOf(true)
// these 5 examples don't throw exceptions
Object.getPrototypeOf(Object)
Object.getPrototypeOf(Object.prototype)
Object.getPrototypeOf(Object.create(null))
Object.getPrototypeOf([])
Object.getPrototypeOf({})
-
Note checking if
typeofis "object" or "function" may not work with host objects, which are allowed to return other things, e.g. in IE ActiveX objects used to return "unknown". – Oriol Jun 16 '15 at 11:58 -
14
-
4
-
3@Illuminator arrays are objects in Javascript, as I mentioned in my answer. – Matt Fenwick Apr 8 '16 at 14:20
-
@MattFenwick OK. So the best solution is your function (
function isObject(val) { if (val === null) ...). My understanding is right? – Illuminator Apr 9 '16 at 6:46
The official underscore.js uses this check to find out if something is really an object
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
-
35In javascript an array is also an object, so most of the time you want to exclude the array:
return obj === Object(obj) && Object.prototype.toString.call(obj) !== '[object Array]'– Daan Jul 12 '13 at 8:57 -
16
-
33Because most of the time you want to distinguish an {} from a [] for example as input in a function – Daan Apr 9 '14 at 9:39
-
5
-
6
Object.prototype.toString.call(myVar) will return:
"[object Object]"if myVar is an object"[object Array]"if myVar is an array- etc.
For more information on this and why it is a good alternative to typeof, check out this article.
-
10I recently learned that
typeof [] === 'object'-->true. That's what you need this method. – Jondlm Aug 11 '13 at 5:29 -
2@Christophe Doesn't distinguish between primitives and objects.
Object.prototype.toString.call(3)->"[object Number]".Object.prototype.toString.call(new Number(3))->"[object Number]" – Matt Fenwick Mar 18 '14 at 17:25 -
3@MattFenwick I don't think this is the kind of "object" the OP is trying to identify – Christophe Mar 19 '14 at 5:21
-
3@Christophe why do you think that? IMHO, in the absence of any other definition given by the OP for "object", it seems most reasonable to me to go with the one that is used consistently throughout the ECS spec. – Matt Fenwick Mar 19 '14 at 11:36
-
getType=function(obj){return Object.prototype.toString.call(obj).match(/\[object (\w+)\]/)[1];};– Mr. Polywhirl Nov 17 '14 at 22:08
For simply checking against Object or Array without additional function call (speed). As also posted here.
isArray()
isArray = function(a) {
return (!!a) && (a.constructor === Array);
};
console.log(isArray( )); // false
console.log(isArray( null)); // false
console.log(isArray( true)); // false
console.log(isArray( 1)); // false
console.log(isArray( 'str')); // false
console.log(isArray( {})); // false
console.log(isArray(new Date)); // false
console.log(isArray( [])); // true
isObject() - Note: use for Object literals only, as it returns false for custom objects, like new Date or new YourCustomObject.
isObject = function(a) {
return (!!a) && (a.constructor === Object);
};
console.log(isObject( )); // false
console.log(isObject( null)); // false
console.log(isObject( true)); // false
console.log(isObject( 1)); // false
console.log(isObject( 'str')); // false
console.log(isObject( [])); // false
console.log(isObject(new Date)); // false
console.log(isObject( {})); // true
-
isObjectonly works with object literals. If i create a custom type, create an instance of the type and test it, it returnsfalse– WickyNilliams Dec 2 '13 at 8:20 -
2@zupa: what !!a does? – user1094081 Apr 23 '15 at 10:59
-
2@3000 well, if we leave out the (!!a) part it crashes, because null and undefined have no constructors. (!!a) filters them out. Does that answer your question? – zupa Apr 27 '15 at 15:26
-
1@zupa @3000
Boolean(a)is longer, but far more intuitive. Just don't usenew Boolean(a): (here's why)! – JayVee Aug 20 '15 at 13:32 -
3Surprised the best answer is so far down the page. This basically answers the question- would this be represented in JSON as something starting with a
{character. For the array case, as long as you don't need to support IE < 9, you can useArray.isArray()to determine if something is an array. It passes all the test cases you provided. – Kip Mar 10 '16 at 14:56
I'm fond of simply:
function isObject (item) {
return (typeof item === "object" && !Array.isArray(item) && item !== null);
}
If the item is a JS object, and it's not a JS array, and it's not null…if all three prove true, return true. If any of the three conditions fails, the && test will short-circuit and false will be returned. The null test can be omitted if desired (depending on how you use null).
DOCS:
http://devdocs.io/javascript/operators/typeof
http://devdocs.io/javascript/global_objects/object
-
2What about console.log(isObject(new Date()))? Why should a date be an object but an array not? – schirrmacher Jun 28 '15 at 19:21
-
@1101: I guess I've not needed that edge case. I'm curious if you have? I suppose then I'd add to the returned short circuit
&& !(item instance of Date), or perhaps&& Object.prototype.toString.call(item) !== '[object Date]'if "frame boundaries" are a concern. Hm… – jtheletter Jun 29 '15 at 0:02 -
2@macher Because
new Date()returns an object. An array is from a logical point of view not an object - although JavaScript handles and reports them as such. In practice however, it is not helpful to see them equal, because they are not. An object has nolengthattribute for example and it has no methods like push(). And sometimes you might want to give a function overloaded params, where you need to make a difference between an array or an object especially if other parameters depend on which one was given. – StanE Aug 5 '16 at 22:10 -
3@Oriol I neither wrote that arrays are not objects nor did I wrote that objects can't have a
lengthproperty (I meant that object literals have nolengthattribute by default). I wrote that arrays are not objects from a logical point of view. I'm speaking about program logic. It is sometimes necessary to check if an array is a "real" array and definitely not an "real" object. That's whatArray.isArray()is for. Imagine you have a function which accepts an object or an array of objects. Checking for a special attribute or method is a dirty solution. The native way is always better. – StanE Aug 29 '16 at 21:50 -
1
With function Array.isArray:
function isObject(o) {
return o !== null && typeof o === 'object' && Array.isArray(o) === false;
}
Without function Array.isArray:
Just surprised how many upvotes for wrong answers 😮
Only 1 answer passed my tests!!! Here I've created my simplified version:
function isObject(o) {
return o instanceof Object && o.constructor === Object;
}
As for me, it's clear and simple, and just works! Here my tests:
console.log(isObject({})); // Will return: true
console.log(isObject([])); // Will return: false
console.log(isObject(null)); // Will return: false
console.log(isObject(/.*/)); // Will return: false
console.log(isObject(function () {})); // Will return: false
ONE MORE TIME: not all answers pass this tests !!! 🙈
In case you need to verify that object is instance of particular class you have to check constructor with your particular class, like:
function isDate(o) {
return o instanceof Object && o.constructor === Date;
}
simple test:
var d = new Date();
console.log(isObject(d)); // Will return: false
console.log(isDate(d)); // Will return: true
As result, you will have strict and robust code!
In case you won't create functions like isDate, isError, isRegExp, etc you may consider option to use this generalized functions:
function isObject(o) {
return o instanceof Object && typeof o.constructor === 'function';
}
it won't work correctly for all test cases mentioned earlier, but it's good enough for all objects (plain or constructed).
isObject won't work in case of Object.create(null) because of internal implementation of Object.create which is explained here but you can use isObject in more sophisticated implementation:
function isObject(o, strict = true) {
if (o === null || o === undefined) {
return false;
}
const instanceOfObject = o instanceof Object;
const typeOfObject = typeof o === 'object';
const constructorUndefined = o.constructor === undefined;
const constructorObject = o.constructor === Object;
const typeOfConstructorObject = typeof o.constructor === 'function';
let r;
if (strict === true) {
r = (instanceOfObject || typeOfObject) && (constructorUndefined || constructorObject);
} else {
r = (constructorUndefined || typeOfConstructorObject);
}
return r;
};
There is already created package on npm v1 based on this implementation! And it works for all earlier described test cases! 🙂
-
-
Because this returns false for isObject(myDateObject), this is not an answer to the question. It does not tell if a variable is an object, only if it is an object of a specific class. The question here is for a generic function that returns true for any object. – Yetanotherjosh Jan 13 at 19:09
-
@Yetanotherjosh It is an answer indeed 🤓 you mentioned case which is described in answer, and the point - you have to use
isDatefor yourDateObject with purpose to write robust code otherwise you will have brittleisObjectmethod. – Vladimir Kovpak Jan 19 at 17:03 -
@VladimirKovpak Using
Datein my comment was ill-chosen because yes, the answer does discussDate. ButDateis just one of infinite possible classes and the point holds for any other class. Example:class Foo() { }; var x = new Foo(); isObject(x)returnsfalse. I don't know exactly what the OP's use case is, but it's easy to conceive of scenarios in which having to know about all possible classes and checking specifically against every one of them is going to be infeasible. – Yetanotherjosh Jan 19 at 21:09 -
OK, let's give you this concept first before answering your question, in JavaScript Functions are Object, also null, Object, Arrays and even Date, so as you see there is not a simple way like typeof obj === 'object', so everything mentioned above will return true, but there are ways to check it with writing a function or using JavaScript frameworks, OK:
Now, imagine you have this object that's a real object (not null or function or array):
var obj = {obj1: 'obj1', obj2: 'obj2'};
Pure JavaScript:
//that's how it gets checked in angular framework
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
or
//make sure the second object is capitalised
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
or
function isObject(obj) {
return obj.constructor.toString().indexOf("Object") > -1;
}
or
function isObject(obj) {
return obj instanceof Object;
}
You can simply use one of these functions as above in your code by calling them and it will return true if it's an object:
isObject(obj);
If you are using a JavaScript framework, they usually have prepared these kind of functions for you, these are few of them:
jQuery:
//It returns 'object' if real Object;
jQuery.type(obj);
Angular:
angular.isObject(obj);
Underscore and Lodash:
//(NOTE: in Underscore and Lodash, functions, arrays return true as well but not null)
_.isObject(obj);
-
You also want to check that it isn't an array. so function isObject(obj) { return obj !== null && typeof obj === 'object' && !Array.isArray(obj); } – Matt Goo Apr 3 '17 at 19:51
-
I agree with you, but as you see in the comment, it's how it's done in angularJs and I mention it in the comment in front of the function, they count the Array as an Object ... look at here for more information: docs.angularjs.org/api/ng/function/angular.isObject – Alireza Apr 4 '17 at 0:50
It depends on what you mean with "is an object". If you want everything that is not a primitive, i.e. things that you can set new properties on, this should do the trick:
function isAnyObject(value) {
return value != null && (typeof value === 'object' || typeof value === 'function');
}
It excludes the primitives (plain numbers/NaN/Infinity, plain strings, symbols, true/false, undefined and null) but should return true for everything else (including Number, Boolean and String objects). Note that JS does not define what "host" objects, such as window or console, should return when used with typeof, so those are hard to cover with a check like this.
If you want to know whether something is a "plain" object, i.e. it was created as a literal {} or with Object.create(null), you might do this:
function isPlainObject(value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
return false;
} else {
var prototype = Object.getPrototypeOf(value);
return prototype === null || prototype === Object.prototype;
}
}
Edit 2018: Because Symbol.toStringTag now allows customizing the output of Object.prototype.toString.call(...), the isPlainObject function above might return false in some cases even when the object started its life as a literal. Arguably, by convention an object with a custom string tag isn't exactly a plain object any more, but this has further muddied the definition of what a plain object even is in Javascript.
-
Why is typeof === 'function' considered to be an object? A function is not an object, isn't it? "new myFunc()" will become an object, yes, but a plain function? – StanE Aug 5 '16 at 21:59
-
No, every function is an object in Javascript, regardless of how it was created. You can set properties on them (unless they are frozen), they are
instanceof Object, two identical function literals are not strictly equal, they are passed by reference, etc. – last-child Oct 29 '16 at 10:38
The most reasonable way to check the type of a value seems the typeof operator. The only problem is that it's horribly broken:
- It returns
"object"fornull, which belongs to Null type. - It returns
"function"for callable objects, which belong to Object type. - It can return (almost) anything it wants for non-standard non-callable objects. For example, IE seemed to like
"unknown". The only forbidden results are"function"and primitive types.
typeof is only reliable for non-null primitives. So a way to check if a value is an object would be ensuring that the string returned by typeof does not correspond to a primitive, and that the object is not null. However, the problem is that a future standard could introduce a new primitive type, and our code would consider it to be an object. New types don't appear frequently, but for example ECMAScript 6 introduced the Symbol type.
Therefore, instead of typeof, I only recommend approaches whose result varies depending on if the value is an object or not. The following intends to be a
Comprehensive but not exhaustive list of proper ways to test if a value belongs to the Object type.
ObjectconstructorThe
Objectconstructor coerces the passed argument to an object. If it's already an object, the same object is returned.Therefore, you can use it to coerce the value to an object, and strictly compare that object with the original value.
The following function requires ECMAScript 3, which introduced
===:function isObject(value) { /* Requires ECMAScript 3 or later */ return Object(value) === value; }I like this approach because it's simple and self-descriptive, and an analogous check will also work for booleans, numbers and strings. However, be aware it relies on the global
Objectnot being shadowed nor altered.Constructors
When you instantiate a constructor, it can return a value different than the just-created instance. But that value will be ignored unless it's an object.
The following function requires ECMAScript 3, which allowed constructors to return non-objects. Before ECMAScript 3 that threw an error, but
trystatements didn't exist back then.function isObject(value) { /* Requires ECMAScript 3 or later */ return new function() { return value; }() === value; }While a bit less simple than the previous example, this one does not rely on any global property, and thus might be the safest.
thisvalueOld ECMAScript specifications required the
thisvalue to be an object. ECMAScript 3 introducedFunction.prototype.call, which allowed to call a function with an arbitrarythisvalue, but coerced to an object.ECMAScript 5 introduced a strict mode which removed this behavior, but in sloppy mode we still can (but arguably shouldn't) rely on it.
function isObject(value) { /* Requires ECMAScript 3 or later in sloppy mode */ return function() { return this === value; }.call(value); }[[Prototype]]
All ordinary objects have an internal slot called [[Prototype]], whose value determines from which other object it inherits from. The value can only be an object or
null. Therefore, you can attempt to create an object which inherits from the desired value, and check if it worked.Both
Object.createandObject.getPrototypeOfrequire ECMAScript 5.function isObject(value) { /* Requires ECMAScript 5 or later */ try { Object.create(value); return value !== null; } catch(err) { return false; } }function isObject(value) { /* Requires ECMAScript 5 or later */ function Constructor() {} Constructor.prototype = value; return Object.getPrototypeOf(new Constructor()) === value; }Some new ECMAScript 6 ways
ECMAScript 6 introduces some new indirect ways to check is a value is an object. They use the previously seen approach to pass the value to some code which requires an object, wrapped inside a
trystatement to catch errors. Some hidden examples, not worth commentingfunction isObject(value) { /* Requires ECMAScript 6 or later */ try { Object.setPrototypeOf({}, value); return value !== null; } catch(err) { return false; } }function isObject(value) { /* Requires ECMAScript 6 or later */ try { new WeakSet([value]); return true; } catch(err) { return false; } }
Note: I intentionally skipped some approaches like Object.getPrototypeOf(value) (ES5) and Reflect methods (ES6) because they call essential internal methods which might do nasty things, e.g. if value is a proxy. For safety reasons my examples only reference value without accessing it directly.
-
2"Only my answer and Daan's are entirely correct." is a bit presumptuous given that I entirely disagree with your first two sentences. – zzzzBov Sep 2 '16 at 16:31
-
1@zzzzBov Well, I looked at all answers and they do not ensure to always return the proper answer, except mine and Daan's. I can give reproducible counterexamples to most of them. The others recommend checking if typeof returns "function" or "object", but as I explained, the spec allows other results for some objects. Matt Fenwick's answer contains the same correct answer as Daan's, but also contains incorrect ones. – Oriol Sep 2 '16 at 16:59
-
1I disagreed with the premise that your answer is "entirely correct", arguing that others "do not ensure to always return the proper answer" does not refute my position in any way. Additionally, the question does not make any claims regarding what input should produce what output. – zzzzBov Sep 2 '16 at 17:04
-
1@zzzzBov The question asks how to check if something is an object. ECMAScript defines what an object is, so I use that definition. I can't see any other reasonable interpretation. Answers that do other things (like excluding arrays) can be useful in some circumstances, but they don't check if something is an object. – Oriol Sep 2 '16 at 17:28
-
@Oriol Perhaps you could provide an Answer to this Question Why is there not a built-in method in JavaScript to check if an object is a plain object? ? – guest271314 Nov 7 '16 at 2:35
Try this
if (objectName instanceof Object == false) {
alert('Not an object');
}
else {
alert('An object');
}
-
11
-
3This misses two cases:
Object.prototype instanceof Object-> false.Object.create(null) instanceof Object-> false. – Matt Fenwick Mar 18 '14 at 14:45 -
-
Ready to use functions for checking
function isObject(o) {
return null != o &&
typeof o === 'object' &&
Object.prototype.toString.call(o) === '[object Object]';
}
function isDerivedObject(o) {
return !isObject(o) &&
null != o &&
(typeof o === 'object' || typeof o === 'function') &&
/^\[object /.test(Object.prototype.toString.call(o));
}
// Loose equality operator (==) is intentionally used to check
// for undefined too
// Also note that, even null is an object, within isDerivedObject
// function we skip that and always return false for null
Explanation
In Javascript,
null,Object,Array,Dateandfunctions are all objects. Although,nullis bit contrived. So, it's better to check for thenullfirst, to detect it's not null.Checking for
typeof o === 'object'guarantees thatois an object. Without this check,Object.prototype.toStringwould be meaningless, since it would return object for everthing, even forundefinedandnull! For example:toString(undefined)returns[object Undefined]!After
typeof o === 'object'check, toString.call(o) is a great method to check whetherois an object, a derived object likeArray,Dateor afunction.In
isDerivedObjectfunction, it checks for theois 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
function isObject(o) {
return null != o &&
typeof o === 'object' &&
Object.prototype.toString.call(o) === '[object Object]';
}
function isDerivedObject(o) {
return !isObject(o) &&
null != o &&
(typeof o === 'object' || typeof o === 'function') &&
/^\[object /.test(Object.prototype.toString.call(o));
}
// TESTS
// is null an object?
console.log(
'is null an object?', isObject(null)
);
console.log(
'is null a derived object?', isDerivedObject(null)
);
// is 1234 an object?
console.log(
'is 1234 an object?', isObject(1234)
);
console.log(
'is 1234 a derived object?', isDerivedObject(1234)
);
// is new Number(1234) an object?
console.log(
'is new Number(1234) an object?', isObject(new Number(1234))
);
console.log(
'is new Number(1234) a derived object?', isDerivedObject(1234)
);
// is function object an object?
console.log(
'is (new (function (){})) an object?',
isObject((new (function (){})))
);
console.log(
'is (new (function (){})) a derived object?',
isObject((new (function (){})))
);
// is {} an object?
console.log(
'is {} an object?', isObject({})
);
console.log(
'is {} a derived object?', isDerivedObject({})
);
// is Array an object?
console.log(
'is Array an object?',
isObject([])
)
console.log(
'is Array a derived object?',
isDerivedObject([])
)
// is Date an object?
console.log(
'is Date an object?', isObject(new Date())
);
console.log(
'is Date a derived object?', isDerivedObject(new Date())
);
// is function an object?
console.log(
'is function an object?', isObject(function(){})
);
console.log(
'is function a derived object?', isDerivedObject(function(){})
);
var a = [1]
typeof a //"object"
a instanceof Object //true
a instanceof Array //true
var b ={a: 1}
b instanceof Object //true
b instanceof Array //false
var c = null
c instanceof Object //false
c instanceof Array //false
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 using instanceof operator. It will eliminate null, but Array has Object in inheritance chain.
So the solution is:
if (myVar instanceof Object && !(myVar instanceof Array)) {
// code for objects
}
Little late... for "plain objects" (i mean, like {'x': 5, 'y': 7}) i have this little snippet:
function isPlainObject(o) {
return ((o === null) || Array.isArray(o) || typeof o == 'function') ?
false
:(typeof o == 'object');
}
It generates the next output:
console.debug(isPlainObject(isPlainObject)); //function, false
console.debug(isPlainObject({'x': 6, 'y': 16})); //literal object, true
console.debug(isPlainObject(5)); //number, false
console.debug(isPlainObject(undefined)); //undefined, false
console.debug(isPlainObject(null)); //null, false
console.debug(isPlainObject('a')); //string, false
console.debug(isPlainObject([])); //array?, false
console.debug(isPlainObject(true)); //bool, false
console.debug(isPlainObject(false)); //bool, false
It always works for me. If will return "true" only if the type of "o" is "object", but no null, or array, or function. :)
-
As mentioned in the previous answers your approach will fail in case of the Date object. – Grzegorz Pawlik Mar 20 '17 at 20:49
lodash has isPlainObject, which might be what many who come to this page are looking for. It returns false when give a function or array.
-
Perfect! I knew about
_.isObjectwhich matches what JS considers an object. But what I usually need is to differentiate between e.g. an object literal and an array, which is exactly what_.isPlainObjectlets me do. – lime Dec 16 '14 at 11:11
When everything else fails, I use this:
var isObject = function(item) {
return item.constructor.name === "Object";
};
-
9
-
1Why the string comparison, why not simply
item.constructor === Object? – K3---rnc Feb 27 '16 at 23:20 -
nullthrows an exceptionUncaught TypeError: Cannot read property 'constructor' of null(…)– Vitim.us May 17 '16 at 14:08 -
@rounce I am aiming to support older IE versions, why does it not work in IE? Because of the
indexOfor because ofconstructor.name? – Jankapunkt Jan 24 at 14:15
This will work. It is a function that returns true, false, or possibly null.
const isObject = obj => obj && obj.constructor && obj.constructor === Object;
console.log(isObject({})); // true
console.log(isObject([])); // false
console.log(isObject(new Function)); // false
console.log(isObject(new Number(123))); // false
console.log(isObject(null)); // null
-
2@SeregPie In future you should refrain from editing code in answers. As this answer stands, when testing I did obtain
nullas the result for the final test rather thanfalse. See When should I make edits to code? – Nick A Dec 13 '17 at 11:36
Return Types
typeof JavaScript constructors and objects (including null) returns "object"
console.log(typeof null, typeof [], typeof {})
Checking on Their constructors
Checking on their constructor property returns function with their names.
console.log(({}).constructor) // returns a function with name "Object"
console.log(([]).constructor) // returns a function with name "Array"
console.log((null).constructor) //throws an error because null does not actually have a property
Introducing Function.name
Function.name returns a readonly name of a function or "anonymous" for closures.
console.log(({}).constructor.name) // returns "Object"
console.log(([]).constructor.name) // returns "Array"
console.log((null).constructor.name) //throws an error because null does not actually have a property
Final code
function isAnObject(obj)
{
if(obj==null) return false;
return obj.constructor.name.toLowerCase() === "object"
}
console.log(isAnObject({})) // return true
console.log(isAnObject([])) // returns false
console.log(isAnObject(null)) // return false
Note: Function.name might not work in IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility
if(typeof value === 'object' && value.constructor === Object)
{
console.log("This is an object");
}
The Ramda functional library has a wonderful function for detecting JavaScript types.
Paraphrasing the full function:
function type(val) {
return val === null ? 'Null' :
val === undefined ? 'Undefined' :
Object.prototype.toString.call(val).slice(8, -1);
}
I had to laugh when I realized how simple and beautiful the solution was.
Example usage from Ramda documentation:
R.type({}); //=> "Object"
R.type(1); //=> "Number"
R.type(false); //=> "Boolean"
R.type('s'); //=> "String"
R.type(null); //=> "Null"
R.type([]); //=> "Array"
R.type(/[A-z]/); //=> "RegExp"
R.type(() => {}); //=> "Function"
R.type(undefined); //=> "Undefined"
var isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
!!obj is shorthand for checking if object is truthy ( to filter out null/undefined)
What I like to use is this
function isObject (obj) {
return typeof(obj) == "object"
&& !Array.isArray(obj)
&& obj != null
&& obj != ""
&& !(obj instanceof String) }
I think in most of the cases a Date must pass the check as an Object, so I do not filter dates out
i found a "new" way to do just this kind of type checking from this SO question: Why does instanceof return false for some literals?
from that, i created a function for type checking as follows:
function isVarTypeOf(_var, _type){
try {
return _var.constructor === _type;
} catch(ex) {
return false; //fallback for null or undefined
}
}
then you can just do:
console.log(isVarTypeOf('asdf', String)); // returns true
console.log(isVarTypeOf(new String('asdf'), String)); // returns true
console.log(isVarTypeOf(123, String)); // returns false
console.log(isVarTypeOf(123, Number)); // returns true
console.log(isVarTypeOf(new Date(), String)); // returns false
console.log(isVarTypeOf(new Date(), Number)); // returns false
console.log(isVarTypeOf(new Date(), Date)); // returns true
console.log(isVarTypeOf([], Object)); // returns false
console.log(isVarTypeOf([], Array)); // returns true
console.log(isVarTypeOf({}, Object)); // returns true
console.log(isVarTypeOf({}, Array)); // returns false
console.log(isVarTypeOf(null, Object)); // returns false
console.log(isVarTypeOf(undefined, Object)); // returns false
console.log(isVarTypeOf(false, Boolean)); // returns true
this is tested on Chrome 56, Firefox 52, Microsoft Edge 38, Internet Explorer 11, Opera 43
edit:
if you also want to check if a variable is null or undefined, you can use this instead:
function isVarTypeOf(_var, _type){
try {
return _var.constructor === _type;
} catch(ex) {
return _var == _type; //null and undefined are considered the same
// or you can use === if you want to differentiate them
}
}
var a = undefined, b = null;
console.log(isVarTypeOf(a, undefined)) // returns true
console.log(isVarTypeOf(b, undefined)) // returns true
console.log(isVarTypeOf(a, null)) // returns true
update from inanc's comment: challenge accepted :D
if you want to loose compare objects you can try this way:
function isVarTypeOf(_var, _type, looseCompare){
if (!looseCompare){
try {
return _var.constructor === _type;
} catch(ex){
return _var == _type;
}
} else {
try{
switch(_var.constructor){
case Number:
case Function:
case Boolean:
case Symbol:
case Date:
case String:
case RegExp:
// add all standard objects you want to differentiate here
return _var.constructor === _type;
case Error:
case EvalError:
case RangeError:
case ReferenceError:
case SyntaxError:
case TypeError:
case URIError:
// all errors are considered the same when compared to generic Error
return (_type === Error ? Error : _var.constructor) === _type;
case Array:
case Int8Array:
case Uint8Array:
case Uint8ClampedArray:
case Int16Array:
case Uint16Array:
case Int32Array:
case Uint32Array:
case Float32Array:
case Float64Array:
// all types of array are considered the same when compared to generic Array
return (_type === Array ? Array : _var.constructor) === _type;
case Object:
default:
// the remaining are considered as custom class/object, so treat it as object when compared to generic Object
return (_type === Object ? Object : _var.constructor) === _type;
}
} catch(ex){
return _var == _type; //null and undefined are considered the same
// or you can use === if you want to differentiate them
}
}
}
that way, you can do just like inanc's comment:
isVarTypeOf(new (function Foo(){}), Object); // returns false
isVarTypeOf(new (function Foo(){}), Object, true); // returns true
or
Foo = function(){};
Bar = function(){};
isVarTypeOf(new Foo(), Object); // returns false
isVarTypeOf(new Foo(), Object, true); // returns true
isVarTypeOf(new Bar(), Foo, true); // returns false
isVarTypeOf(new Bar(), Bar, true); // returns true
isVarTypeOf(new Bar(), Bar); // returns true
-
This can't detect whether a new class is an object. isVarTypeOf(new (function Foo() {}), Object) // This returns false instead of true. See my answer below for proper checking. – Inanc Gumus May 10 '17 at 7:49
-
However, you can use
instanceofto check for objects. Still, this is not an exact science. – Inanc Gumus May 10 '17 at 7:53 -
@inanc, well that is because
new Foo()returns aFooobject, same asnew String()returns aStringobject, ornew Date()returns aDateobject, you can doFoo = function(){}; isVarTypeOf(new Foo(), Foo);also – am05mhz May 12 '17 at 2:54 -
Yeah, that's what I say actually: You aren't checking whether it's an object right now. – Inanc Gumus May 12 '17 at 5:00
-
@inanc Cheers, I was looking for a way to do type checking (not just object), got to this page and the other page, then I got too excited that I forgot the context of this question, my bad :) – am05mhz May 12 '17 at 6:47
My God, too much confusion in other answers.
Short Answer
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array)
To test this simply run the following statements in chrome console.
Case 1.
var anyVar = {};
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // true
Case 2.
anyVar = [];
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // false
Case 3.
anyVar = null;
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array); // false
Explanation
Okay.Let's break it down
typeof anyVar == 'object' is returned true from three candidates - [], {} and null,
anyVar instanceof Object narrows down these candidates to two - [], {}
!(anyVar instanceof Array) narrows to only one - {}
Drum rolls please!
By this you may have already learnt how to check for Array in Javascript.
If you are already using AngularJS then it has a built in method which will check if its an object (without accepting null).
angular.isObject(...)
use typeof(my_obj) will tells which type of variable it is.
if it is object will show 'object'
simple JS function,
function isObj(v) {
return typeof(v) == "object"
}
Eg:
function isObj(v) {
return typeof(v) == "object"
}
var samp_obj = {
"a" : 1,
"b" : 2,
"c" : 3
}
var num = 10;
var txt = "Hello World!"
var_collection = [samp_obj, num, txt]
for (var i in var_collection) {
if(isObj(var_collection[i])) {
console.log("yes it is object")
}
else {
console.log("No it is "+ typeof(var_collection[i]))
}
}
Its depends on use-case, if we do not want to allow array and functions to be an Object, we can use the underscore.js builtin functions.
function xyz (obj) {
if (_.isObject(obj) && !_.isFunction(obj) && !.isArray(obj)) {
// now its sure that obj is an object
}
}
Mostly typeof obj[index] === 'object'is used, but it will return also function and #document which are an objects. It depends up to you if it need to be included in the result.
Basically you can do a test code that filtering out if a particular elements is an object by checking the output in your console. Here you can run a code just for a sample:
function cekObject(obj, index) {
if (!obj.tagName) {
//test case #1
if (typeof obj === 'object') {
console.log('obj['+ index +'] is listed as an object');
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<script>
function updateFilters() {
var object = $('.j-image');
$('.juicer-feed').empty();
for(var index in object) {
cekObject(object[index], index);
};
}
</script>
<ul class="juicer-feed" data-feed-id="chetabahana" data-after="updateFilters()"></ul>
<script src="https://assets.juicer.io/embed.js"></script>
If you would like to check if the prototype for an object solely comes from Object. Filters out String, Number, Array, Arguments, etc.
function isObject(n) {
if (n == null) return false;
return Object.prototype.toString.call(n) === '[object Object]';
}
-
1this is the best way but I would make it even easier by on the 2nd line:
return Object.prototype.toString.call(n) === '[object Object]'– mesqueeb Jun 10 at 4:19 -
protected by Oriol Sep 3 '16 at 15:56
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
nullis an object). – user395760 Dec 14 '11 at 20:46