How do you check if a value is an object in JavaScript?
-
5A variable is a variable. It may refer to an object. Also, you may want to define "object" - as the answers and comments show, there are various conflicting definitions (e.g. whether `null` is an object). – Dec 14 '11 at 20:46
-
8OP, IMO you should accept @Daan's answer as it is the best solution and should be listed above other answers so it is seen first. (No offense to others who also have good answers.) – tiffon Nov 17 '15 at 21:11
-
3IMHO it really depends on what you (the one seeking for an answer to this question) consider an Object, and why you are checking it. This question gives different answers if you are trying to distinguish Arrays (that **are** Objects) from *other* Objects or if you are trying to separate scalar values from "vectors". And whether null (that **is** an Object, according to typeof) or Functions (that **are** Objects) should be excluded or not, it really depends on why you are checking it. That's why there are so many answers and most of them, in context, are correct. – FrancescoMM Feb 08 '17 at 11:52
-
const isEmpty = thing => { typeof thing === "object" ? !thing || !Object.keys(thing).length : !thing && thing !== 0 }; – Mayur Shedage Jul 27 '18 at 09:14
-
@user395760 Literally every definition in programming conflicts with another definition. The definition that makes the most sense to OP is `A javascript object is a javascript object such as '{}'`. Explain to me why null would be considered an object ever? If you consider `null` an object, you may as well consider every single variable in javascript an `object`. – ICW Dec 12 '19 at 19:06
-
1It would be great if you could start by saying what exactly *you* mean by "is an Object". (Or, say explicitly that part of the answer you're seeking is to nail down various popular meanings of "is an object" and then differentiate between them.) Lacking that, everyone is talking past each other. – Don Hatch Dec 26 '19 at 13:43
-
1@tiffon How about a to the point answer at https://stackoverflow.com/a/52478680/1096194. I wrote this when I was overwhelmed by seeing the length of detail in many of the highest voted answers. I believe it deserves a lot more visibility. – HalfWebDev Jun 08 '20 at 10:40
-
In Vue 3 (composition API) when use "typeof variable" - I get "Object" everithing because of Proxy. Then i use just a " if (variable.length)" -> for Oblject it'll be "undefined" and you can use if statement. – Михаил Dec 30 '21 at 20:09
-
Very related: https://stackoverflow.com/questions/38304401/javascript-check-if-dictionary (dupe debatable)... and maybe more what most people finding this page are thinking of, I assume. I.e. looking specifically for dictionaries. Well, it's what I was thinking of, anyways. – Jason C May 27 '22 at 05:19
-
Use lodash _.isPlainObject which covers all the basic use cases and more - https://lodash.com/docs/#isPlainObject – danday74 Jul 28 '22 at 22:26
55 Answers
If typeof yourVariable === 'object'
, it's an object or null
.
If you want null
, arrays or functions to be excluded, just make it:
if (
typeof yourVariable === 'object' &&
!Array.isArray(yourVariable) &&
yourVariable !== null
) {
executeSomeCode();
}
-
@RightSaidFred: Well, like delnan said, I guess that's kind of a question of definitions. I would actually be inclined to say null is an object based on the typeof operator's say-so. But I guess you're right that it's not the most useful definition. That's just my personal mental model of the language, where "is-object" and "is-null" are two separate flags. – Chuck Dec 14 '11 at 21:08
-
1Yeah, I'm not sure what delnan meant by that, but ECMAScript 5 [defines the null value](http://es5.github.com/#x4.3.11) as *"primitive value that represents the intentional absence of any object value."* in spite of the fact that its `typeof` operator [claims otherwise](http://es5.github.com/#x11.4.3). Not sure about the wording in ES3. This is [set to be fixed](http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null) in ES6. In any case, `null` doesn't behave in any way like an object. Your `yourVariable != null` is the common approach so +1. – RightSaidFred Dec 14 '11 at 21:53
-
@RightSaidFred: Wow, ES3 agrees. I always just trusted the typeof operator and figured it was an artifact of Java's influence on the object system. I was clearly wrong. – Chuck Dec 14 '11 at 22:27
-
77
-
5
-
11@RightSaidFred Seems that `typeof null == 'object'` will not be fixed in [ES6](http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null). 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 03 '13 at 10:50
-
1
-
2@Orion the simple answer is that arrays are considered to be objects. For a more detailed answer, you'll have to read up on [`typeof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) because it has a few special cases that don't necessarily make a whole lot of sense. If you're trying to differentiate between arrays and objects which are not arrays, then you definitely don't want to use `typeof`. – Matt Fenwick Dec 01 '14 at 15:48
-
3Would it not be more reliable to do `yourVariable && typeof yourVariable === 'object` rather than explicitly checking for `null`? What if `yourVariable` is `undefined`? – James Oct 28 '15 at 10:45
-
For noobs: JavaScript doesn't know what "If" means, it must be "if" (lowercase) or you'll get weird errors that will make you rip out your chest hairs – Nick Steele Nov 08 '15 at 01:36
-
This could also be used as an alternative for getting rid of null values for some cases: yourVariable = yourVariable || {}; if (typeof yourVariable === 'object') { // do something } – skud Jan 21 '16 at 17:40
-
16@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 09:48
-
1`yourVariable !== null && typeof yourVariable === 'object' && !Array.isArray( yourVariable )` Arrays type evaluates to `"object"`. Added a check for arrays – X_Trust Oct 13 '16 at 14:47
-
typeof [] is also "object" So how would we tell the difference without using instanceof which is rather slow. – Urasquirrel Oct 21 '16 at 19:59
-
3The solution above does not take into account a RegExp or Date object, if you need to to support these object types you'll want to perform a check first. `if( val && type val !== 'object && Object.prototype.toString.call(val) !== '[object RegExp]' && Object.prototype.toString.call(val) !== '[object Date]') {...}` – Troy Watt Nov 07 '17 at 04:23
-
27Downvoted because an array is also considered an object, so you should also check `Array.isArray(yourVariable)`. – Alexander Flenniken Nov 29 '17 at 22:34
-
1@AlexanderFlenniken There is no need because `typeof []` returns `"object"`, arrays will be included in the check by default. – doubleOrt Dec 28 '17 at 17:09
-
-
2Normal objects are always considered to be truthy, while `null` is considered falsy. This means the second version could also be written as `typeof yourVariable === 'object' && yourVariable` – 3limin4t0r Jun 04 '19 at 19:04
-
*Everything is an Object so `true` will do* - That is okay to say as much as *Functions are also objects and should be included*. But the programmer should have the freedom to be specific and exclude eventual functions sliped in! Or be able to sort out objects among functions! Or to have an argument that can be a `function(){}` closure or object `{}`. – Jun 26 '19 at 23:08
-
1This is the answer that worked for me to check if loaded module brings a **declared** (must be checked before) **defined** (not function or array or null but) **object**. The first comment everyone now can flag as *not needed* because it is answered by `&& yourVariable !== null`. And also should be flaged is the accepted answer because handwaving is not an anser at all. Read it again and wake up: *Try using `typeof(var)` and/or `var instanceof something`. EDIT: This answer gives an **idea** ...* Sometimes answer is shosen because no else has answered. – Jun 26 '19 at 23:24
-
Hi there are also other cases that are `typeof 'object'`: `Buffer`, `RegExp`, `Date` – TOPKAT Dec 04 '19 at 20:22
-
1This doesn't work with Map() or other objects. U need use `Object.prototype.toString.call(obj)` if u want to check that object is Object – Vasiliy Rusin Apr 21 '21 at 16:35
-
It seems that much of the discussion around this question is because of the definition of what an "object" is. I came across this question looking for the following definition: *something that will be serialized as an object when using JSON.stringify*, and it seems that this is the best answer in that case. – felipou Jun 01 '22 at 15:01
-
The formal definition of a JavaScript object includes functions, arrays, boxed primitives, and doesn't include null. To construct such a check, you can do `(typeof obj === 'object' && obj !== null) || typeof obj === 'function'`. Alternatively, this small piece of code will do the exact same thing: `Object(obj) === obj`. I would highly recommend you make your checks using this formal definition unless you have a good reason to deviate. – Scotty Jamison Sep 22 '22 at 14:24
-
-
`const isObject = (value) => Object.prototype.toString.call(value) === '[object Object]';` – Juan Nov 20 '22 at 18:49
UPDATE:
This answer is incomplete and gives misleading results. For example, null
is also considered of type object
in JavaScript, not to mention several other edge cases. Follow the recommendation below and move on to other "most upvoted (and correct!) answer":
typeof yourVariable === 'object' && yourVariable !== null
Original answer:
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.

- 30,204
- 37
- 167
- 263

- 138,757
- 24
- 193
- 173
-
@MichaelKrelin-hacker: I'll do my best. ;) But what about `myvar instanceof(something)` or `(myvar)instanceof(something)`? ;) – RightSaidFred Dec 14 '11 at 21:59
-
@MichaelKrelin-hacker: For me it's clear... `typeof x` with parantheses looks like a function, but `instanceof` doesn't, no matter what you do. No idea why `typeof` is not a function (I don't know enough JS to decide if it could be). – maaartinus Apr 06 '14 at 13:34
-
@maaartinus, it could as you can have `function fntypeof(x){return typeof x}`. Moreover, you can have `function fninstanceof(x,y){return x instanceof y}`. The reason why it's operator is probably because it is modelled after c `sizeof` that happens at compile tim. And the primary reason to use extensive parentheses in the code for me is that I don't always remember precedence ;) – Michael Krelin - hacker Apr 06 '14 at 18:11
-
146This answer is incorrect. `typeof` returns 'object' for null, which is not an object, and `instanceof` doesn't work for objects created using `Object.create(null)`. – Nikolai Apr 08 '14 at 21:12
-
3
-
2Consider with this statement that the arrays are objects too, so if your code look like typeof(test) and test is an array then the result will be "object" – Iran Reyes Feb 09 '15 at 23:07
-
20Arrays will also return as "objects" as in: `someArray instanceof Object //true` or `typeof someArray === 'object' // true`. What about: `Object.prototype.toString.call(someObject) === "[object Object]"`, or `"[object Array]"` if you're trying to detect an array? – Con Antonakos Jun 19 '15 at 14:52
-
9@Jonathan, there are better reasons for downvoting my answer, do you by chance have military background? :) – Michael Krelin - hacker Sep 08 '15 at 11:54
-
10This should not be the accepted answer. Beyond the stylistic concerns raised by Jonathan, it is simply incorrect and does not bring up the very important subtleties in e.g. @matt-fenwick's answer. – last-child Jan 18 '16 at 20:27
-
-
@Andrew, read the next answer, the one that has more votes and perhaps deserves it. – Michael Krelin - hacker Mar 04 '16 at 22:41
-
1
-
1@RightSaidFred excellent point. So for those who wish to use parentheses for grouping, it would be clearer to use the parentheses like `(typeof something)==='object'` instead of like `typeof(something)==='object'`. – maurice Jul 19 '16 at 22:57
-
@maurice, true, that's what I do most of the time nowadays. Though I still hate it when people tell each other which one of the technically equivalent expression to use. I suppress the urge to do so when I have one (which happens a lot, admittedly:)). – Michael Krelin - hacker Jul 20 '16 at 10:55
-
"foo instanceof Object" can return true for functions and objects, so typeof is better. – CStff Dec 21 '16 at 15:22
-
2This answer is bad because it doesn't tell you about the secret null problem in the original answer or the edit, because the answer doesn't tell you how to even use the typeof in the original answer or edit (what to compare to?), and because in the edit you wrote so much useless text that did not improve the answer. Vote down. – Andrew Dec 23 '16 at 14:16
-
` (arr[index] instanceof Object || arr[index] instanceof Array)` === `Array instanceof Object` – Sep 01 '17 at 02:24
-
agree that this answer is dangerously incomplete (and thus wrong in context) [Matt Fenwick's answer](https://stackoverflow.com/a/22482737/679950) should be the accepted one – pentaphobe Sep 04 '17 at 03:48
-
Check out this article: http://tobyho.com/2011/01/28/checking-types-in-javascript/ – Iran Reyes Oct 20 '17 at 16:32
-
2Downvoted because you should at the very least mention `typeof null == "object"`. – doubleOrt Dec 28 '17 at 17:17
-
good resource about null problem: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#Additional_information – Serhat Ates Oct 15 '18 at 06:21
-
2Never be specific is *The winner pattern*: **Try using** `blabla` **and/or** `blabla` **something. EDIT: This answer gives an idea** blabla ... – Jun 26 '19 at 22:56
-
@RightSaidFred can you explain why you say `typeof(foo)` confuses people? I sometimes use it simply because, it seems to me, the question of whether `typeof` is an operator or function really doesn't matter in most cases, and I don't want to waste my time looking it up to remind myself. I don't think it's fair to say I'm confused; I'm just making things simple when they don't need to be complicated. – Don Hatch Dec 26 '19 at 14:01
-
@DonHatch, I guess confused are people who see the code and obviously it's non-obvious with this syntax. Not sure if it has any disastrous consequences tho. – Michael Krelin - hacker Dec 26 '19 at 18:22
-
How about deleting this answer then? There's no way to flag an answer as deprecated? – Graham P Heath Jun 01 '20 at 21:44
-
we can check array : var yourVariable = [] typeof yourVariable === 'object' && yourVariable !== null && !Array.isArray(yourVariable) – kuldeep chopra Mar 23 '21 at 03:03
-
-
This is wrong. Include `typeof x == "function"`. Functions are objects. – Hunter Kohler Aug 29 '21 at 22:20
-
simpified: `isObject(field) { return typeof field === 'object' && field !== null; }` – Bullsized Mar 01 '22 at 12:58
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 7 primitive data types: string, number, bigint, boolean, undefined, symbol, and null.
What's a primitive?
3
'abc'
true
null
undefined
What's an object (i.e. not a primitive)?
Object.prototype
- everything descended from
Object.prototype
Function.prototype
Object
Function
function C(){}
-- user-defined functions
C.prototype
-- the prototype property of a user-defined function: this is notC
s prototypenew C()
-- "new"-ing a user-defined function
Math
Array.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({})

- 516
- 1
- 6
- 17

- 48,199
- 22
- 128
- 192
-
Note checking if `typeof` is "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
-
46
-
6
-
22@Illuminator arrays *are* objects in Javascript, as I mentioned in my answer. – Matt Fenwick Apr 08 '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 09 '16 at 06:46
-
`new Number(3)` is an object and not a primitive, so it shouldn't be in the list of examples of false positives. – Macil Jun 09 '16 at 23:33
-
1`getPrototypeOf` does not work e.g. with revoked proxies, which are objects but throw. – Oriol Aug 28 '16 at 01:03
-
The object / primitive dichotomy is confusing and seems arbitrary. The cleanest definition that has an impact on the way we code is whether something has value semantics on copy / argument passing or not. In other words if I create a new binding `let b = a` or pass `a` as an argument in a function call `foo(a)` can I change `a` through the new binding `b` or from inside the `foo` function? Seen in that light it is clear why functions, objects and arrays are "objects" whereas strings, numbers, null, undefined, NaN are "primitives". Just my 2c. – Marcus Junius Brutus Dec 11 '16 at 22:45
-
6Why not `({}).toString.apply(obj) === '[object Object]'` this distinguishes between arrays and objects that are not arrays – MauricioJuanes Nov 06 '18 at 22:09
-
1
-
"typeof" approach looks like much faster then "===Object(..)" https://jsbench.me/epk80dx8xr/1 – Yuri Gor Mar 20 '20 at 16:21
underscore.js provides the following method to find out if something is really an object:
_.isObject = function(obj) {
return obj === Object(obj);
};
UPDATE
Because of a previous bug in V8 and minor micro speed optimization, the method looks as follows since underscore.js 1.7.0 (August 2014):
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};

- 5,211
- 1
- 24
- 48

- 7,685
- 5
- 43
- 52
-
70In 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 08:57
-
28
-
90Because most of the time you want to distinguish an {} from a [] for example as input in a function – Daan Apr 09 '14 at 09:39
-
6
-
1This is the best answer. `Object` converts to an object, and `===` ensures `obj` is the same object. – Oriol Jun 16 '15 at 12:00
-
7
-
5
-
2[My answer](http://stackoverflow.com/a/39187058/1529630) is more complete but this is the only one among the others which works properly for all possible values. Hopefully the bounty sign will make this answer stand out and reach the top. – Oriol Sep 04 '16 at 20:30
-
2Nothing works for everything. Some objects are iterable and should be handled as arrays even though they are objects, depending on the application. – Samuel Danielson Mar 04 '17 at 09:58
-
I can't believe this ended up on page two. This is the quickest and most efficient way to make sure that using the `in` operator won't cause an error. – Domino Nov 02 '18 at 21:52
-
So now we can install Underscore.js and use `_.isObject(x) && typeof x !== 'function'` to check if x is an object and nothing else :P – Jun 26 '19 at 19:43
-
This is technically *not* vanilla javascript though, which this overflow focuses on -- it's code someone else essentially wrote in JS which won't work without Underscore being included. Maybe there should be overflows (is that even a term on here?) for the main frameworks and libraries like JQuery, Underscore, etc. – Netside Jul 12 '20 at 22:12
-
This is the correct answer... It will capture objects, classes, functions, and arrays, but not `null`. All 4 of those are extensible via. `Object.defineProperty()` type functions, and that is what counts most. – Andrew Feb 06 '23 at 21:43
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.

- 109,027
- 88
- 289
- 474

- 27,383
- 28
- 97
- 140
-
18I recently learned that `typeof [] === 'object'` --> `true`. That's what you need this method. – Jondlm Aug 11 '13 at 05:29
-
5@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
-
8@MattFenwick I don't think this is the kind of "object" the OP is trying to identify – Christophe Mar 19 '14 at 05: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
-
Many types of objects give different results like '[object Date]' or '[object Error]'. – Macil Jun 09 '16 at 23:37
-
@AgentME right, there are many more. I just said "etc.", listing them all wouldn't add much value to my answer. – Christophe Jun 11 '16 at 01:05
-
My point was that if someone wants to detect objects including Dates, Errors, and everything else, then doing a comparison against "[object Object]" isn't going to work. – Macil Jun 15 '16 at 20:12
-
this is even better: `Object.prototype.toString.call(val).slice(8, -1);` – Matteo May 24 '21 at 02:28
-
I find this the most readable: `Object.prototype.toString.call(isObj).endsWith('Object]')` – dain Jun 30 '22 at 17:32
-
I like this one, in my case to check if primitive: I can compare the ending type of the string, with a list of primitives (string, symbol, number, boolean, undefined) – OtaconKiko Oct 25 '22 at 16:20
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
isLiteralObject()
- Note: use for Object
literals only, as it returns false
for custom objects, like new Date
or new YourCustomObject
.
isLiteralObject = function(a) {
return (!!a) && (a.constructor === Object);
};
console.log(isLiteralObject( )); // false
console.log(isLiteralObject( null)); // false
console.log(isLiteralObject( true)); // false
console.log(isLiteralObject( 1)); // false
console.log(isLiteralObject( 'str')); // false
console.log(isLiteralObject( [])); // false
console.log(isLiteralObject(new Date)); // false
console.log(isLiteralObject( {})); // true
-
`isObject` only works with object literals. If i create a custom type, create an instance of the type and test it, it returns `false` – WickyNilliams Dec 02 '13 at 08:20
-
@WickyNilliams that's true, the `new Date` testcase was intended to highlight that. Added emphasis in form of a Note, thanks – zupa Dec 02 '13 at 12:09
-
4
-
@3000 `!!a` is boolean type casting in JS. `!a` negates `a`, `!!a` double negates it. – zupa Apr 27 '15 at 08:15
-
-
@3000 Are you about to suggest an alternative? Go ahead. Or elaborate on your question as I'm puzzled. My first thought was, well, to implement the function. – zupa Apr 27 '15 at 14:46
-
@zupa: absolutely not. I was just curious since I don't undestand WHY you did it, that's all :-) – Apr 27 '15 at 14:49
-
8@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@3000 - re: `(!!a)` - the `!` operator is a boolean negation. so in pseudo-code this is `not(not(a))` so if `a` is related to `false` (any of `null`, `false`, `0`, `""`) then the result is a `false`. it `a` is not related to `false` then the result is a `true`. – Jesse Chisholm May 07 '15 at 21:44
-
3@zupa @3000 `Boolean(a)` is longer, but far more intuitive. Just don't use `new Boolean(a)`: ([here's why](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description))! – Jeroen Versteeg Aug 20 '15 at 13:32
-
26Surprised 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 use `Array.isArray()` to determine if something is an array. It passes all the test cases you provided. – Kip Mar 10 '16 at 14:56
-
@Kip This does not answer the question "would this be represented in JSON as something starting with a { character". `class Foo { }; var x = new Foo(); x.someProperty = 1; JSON.stringify({test: x}) // returns '{"test":{"someProperty":1}}'`. This checks for constructor to equal `Object` (which is definitely not true for all objects). But that's not the criteria for JSON curly brace encoding. – Yetanotherjosh Jan 13 '18 at 19:15
-
1@zupa @3000 @JayVee `return a && (a.constructor === Object);` works as well. I don't see the need for the double negative – Brad Kent Jul 03 '19 at 19:48
-
3@BradKent Without the double negative `!!a` `isObject(null)` would return `null` instead of `false` – AKG Aug 13 '19 at 22:43
-
1
-
`isObject` doesn’t work for `Object.create(null)`, and it doesn’t work for `document.all` (for the wrong reason). Why would you exclude functions and objects of other prototypes? – Sebastian Simon May 14 '20 at 18:12
-
@Kip If you're specifically checking for that kind of type, the straightforward check is `JSON.stringify(val).startsWith('{')`. It's not the most performant approach but sometimes gets that job well enough. – Jason C May 27 '22 at 05:16
-
Btw https://stackoverflow.com/questions/38304401/javascript-check-if-dictionary (dupe debatable) is probably more what most people finding this page were thinking of, I assume. I.e. looking specifically for dictionaries. – Jason C May 27 '22 at 05:21
-
This doesn't answer the question. I'm not going to down vote it though because this answer contains more useful information than the top answers. So kudos for explaining how to check if an object was created from an object literal. – PHP Guru Feb 18 '23 at 00:44
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

- 11,022
- 8
- 52
- 58
-
4What 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… – 2540625 Jun 29 '15 at 00:02
-
7@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 no `length` attribute 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 05 '16 at 22:10
-
2@StanE Arrays are definitely objects. Not sure why you think objects can't have a `length` property nor methods like `push`, `Object.create(Array.prototype)` is a trivial counterexample of a non-array object which has these. What makes arrays special is that they are exotic objects with a custom [[DefineOwnProperty]] essential internal method, but they are still objects. – Oriol Aug 28 '16 at 19:50
-
5@Oriol I neither wrote that arrays are not objects nor did I wrote that objects can't have a `length` property (I meant that object literals have no `length` attribute 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 what `Array.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
-
@Oriol your example (`Object.create(Array.prototype)`) might not be the best one since it's `instanceof Array` and methods like `.push` will work like it was an array. – Camilo Martin Sep 07 '16 at 14:16
-
@CamiloMartin I provided a counterexample of a non-array array-like object to demonstrate that "*A [non-array?] object has no length attribute for example and it has no methods like push()*" is blatantly false. My example was array-like deliberately, but it's not an array. `instanceof` only checks inheritance, not behavior. And array methods like `push` are intentionally generic, they don't require array objects. – Oriol Sep 07 '16 at 14:47
-
This is the best answer in my eyes. `&& item !== null` is pointless though since if the item is `null` then `typeof item` will equal `"undefined"` thus `typeof item === "object"` will return false anyway. – Daniel Tonon Oct 01 '16 at 02:08
-
2
-
1
-
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!

- 16,596
- 7
- 59
- 74
-
1best answer! works for many of cases mentioned [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) – prieston Oct 20 '17 at 08:57
-
1Because 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 '18 at 19:09
-
@Yetanotherjosh It is an answer indeed you mentioned case which is described in answer, and the point - you have to use `isDate` for yourDateObject with purpose to write robust code otherwise you will have brittle `isObject` method. – cn007b Jan 19 '18 at 17:03
-
1@VladimirKovpak Using `Date` in my comment was ill-chosen because yes, the answer does discuss `Date`. But `Date` is just one of infinite possible classes and the point holds for any other class. Example: `class Foo() { }; var x = new Foo(); isObject(x)` returns `false`. 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 '18 at 21:09
-
-
Using `instanceof` doesn't work for objects created from `Object.create(null)`. – CMCDragonkai Feb 11 '18 at 05:19
-
@CMCDragonkai Thank you for this case! I've updated answer and also created package on npm. – cn007b Feb 12 '18 at 08:53
Oh My God! I think this could be more shorter than ever, let see this:
Short and Final code
function isObject(obj)
{
return obj != null && obj.constructor.name === "Object"
}
console.log(isObject({})) // returns true
console.log(isObject([])) // returns false
console.log(isObject(null)) // returns false
Explained
Return Types
typeof JavaScript 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

- 129
- 9

- 2,395
- 17
- 20
-
7I really like this one, short and to the point. It only fails on 1 thing as far as I can see. if obj = `Object.create(null)` and quite why you would do that anyway...? – Julian Knight Feb 17 '20 at 20:01
-
If you like, you can exclude that rare case: `return obj != null && obj.constructor && obj.constructor.name === "Object"` The condition 'obj.constructor' returns false because Object.create(null) creates an object with no properties, not even .__proto__ or .constructor. – jkdev Nov 08 '21 at 15:57
-
2Based on your answer, my final (ES11) helper in NodeJS is: `const isObject = (obj) => (obj ?? false)?.constructor?.name === "Object";` Thank you! – szegheo Dec 15 '21 at 10:53
Try this
if (objectName instanceof Object) {
alert('An object');
} else {
alert('Not an object');
}
-
5This misses two cases: `Object.prototype instanceof Object` -> false. `Object.create(null) instanceof Object` -> false. – Matt Fenwick Mar 18 '14 at 14:45
-
1
-
1
-
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);

- 100,211
- 27
- 269
- 172
-
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 03 '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: https://docs.angularjs.org/api/ng/function/angular.isObject – Alireza Apr 04 '17 at 00: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.

- 4,481
- 1
- 21
- 19
-
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 05 '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
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.

- 7,022
- 12
- 65
- 103
-
3Of note, this also returns `false` (as desired) when `anyVar` is a function. – Jamie Birch Feb 12 '19 at 15:34
-
Nice answer @HalfWebDev, but to cater for functions as commented by Jamie Birch, we can do this typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) && typeof anyVar !== 'function' – Sandeep Amarnath May 02 '21 at 15:35
-
1new Date() will return true here. Can fix with !(anyVar instanceof Date) – Tyler Auer Dec 26 '22 at 23:15
Here's an answer with optional chaining, and perhaps the smallest isObj
function for this question.
const isObj = o => o?.constructor === Object;
// True for this
console.log(isObj({})); // object!
// False for these
console.log(isObj(0)); // number
console.log(isObj([])); // array
console.log(isObj('lol')); // string
console.log(isObj(null)); // null
console.log(isObj(undefined)); // undefined
console.log(isObj(() => {})); // function
console.log(isObj(Object)); // class

- 2,044
- 2
- 31
- 32
-
1
-
3@TinyRoy isn't that how it's supposed to be? An error instance is not an object. Let me know if I got something wrong. :) – Jayant Bhawal May 16 '20 at 17:43
-
If your intension is to exclude instances that inherit from Object, then you are right but I see them as objects. They have all the properties of an object. – TinyRoy May 17 '20 at 21:55
-
I believe that is what the question asked. Otherwise basically everything inherits from Object. – Jayant Bhawal May 18 '20 at 08:48
-
-
@PedroFernandesMartins it's the optional chaining operator. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining – Jayant Bhawal Sep 14 '20 at 14:05
-
Wow, i've been waiting my whole life for this knowledge! thks – Pedro Fernandes Martins Sep 15 '20 at 16:22
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.
Object
constructorThe
Object
constructor 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
Object
not 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
try
statements 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.
this
valueOld ECMAScript specifications required the
this
value to be an object. ECMAScript 3 introducedFunction.prototype.call
, which allowed to call a function with an arbitrarythis
value, 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.create
andObject.getPrototypeOf
require 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
try
statement 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.

- 274,082
- 63
- 437
- 513
-
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 02 '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 02 '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 02 '16 at 17:04
-
2@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 02 '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?](http://stackoverflow.com/questions/40456491/why-is-there-not-a-built-in-method-in-javascript-to-check-if-an-object-is-a-plai) ? – guest271314 Nov 07 '16 at 02:35
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
,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
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(){})
);

- 25,195
- 9
- 85
- 101
-
Hi ! Great post but has a minor typo even if it yields correct result: console.log( 'is (new (function (){})) a derived object?', isObject((new (function (){}))) ); – virtual_Black_Whale Oct 07 '20 at 10:48
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' || o.constructor === Date ) ?
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. :)

- 1,183
- 1
- 9
- 16
-
As mentioned in the previous answers your approach will fail in case of the Date object. – Grzegorz Pawlik Mar 20 '17 at 20:49
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) {
return Object.prototype.toString.call(n) === '[object Object]';
}
Or as a single-expression arrow function (ES6+)
const isObject = n => Object.prototype.toString.call(n) === '[object Object]'

- 5,211
- 1
- 24
- 48

- 322
- 2
- 9
-
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 '18 at 04:19
-
1You can also remove the `null` check, because `Object.prototype.toString.call(null) === '[object Null]'` – Gust van de Wal Nov 06 '19 at 00:02
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
}

- 2,342
- 4
- 28
- 36
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.

- 16,515
- 15
- 95
- 114
-
Perfect! I knew about `_.isObject` which 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 `_.isPlainObject` lets me do. – lime Dec 16 '14 at 11:11
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"

- 1,255
- 14
- 25
Performance
Today 2020.09.26 I perform tests on MacOs HighSierra 10.13.6 on Chrome v85, Safari v13.1.2 and Firefox v80 for chosen solutions.
Results
- solutions C and H are fast/fastest on all browsers for all cases
- solutions D and G are slow/slowest on all browsers for all cases
Details
I perform 3 tests cases for solutions A B C D E F G H I J K L M N O P Q R S T U V
- for small object - you can run it HERE
- for big object - you can run it HERE
- for no object - you can run it HERE
Below snippet presents differences between solutions. Solutions A-G give proper answers for chosen cases described by Matt Fenwick
// https://stackoverflow.com/a/14706877/860099
function A(x) {
return x === Object(x);
};
// https://stackoverflow.com/a/42250981/860099
function B(x) {
return _.isObject(x);
}
// https://stackoverflow.com/a/34864175/860099
function C(x) {
return x != null && (typeof x === 'object' || typeof x === 'function');
}
// https://stackoverflow.com/a/39187058/860099
function D(x) {
return new function() { return x; }() === x;
}
// https://stackoverflow.com/a/39187058/860099
function E(x) {
return function() { return this === x; }.call(x);
}
// https://stackoverflow.com/a/39187058/860099
function F(x) { /* Requires ECMAScript 5 or later */
try {
Object.create(x);
return x !== null;
} catch(err) {
return false;
}
}
// https://stackoverflow.com/a/39187058/860099
function G(x) { /* Requires ECMAScript 5 or later */
function Constructor() {}
Constructor.prototype = x;
return Object.getPrototypeOf(new Constructor()) === x;
}
// https://stackoverflow.com/a/8511332/860099
function H(x) {
return typeof x === 'object' && x !== null
}
// https://stackoverflow.com/a/25715455/860099
function I(x) {
return (typeof x === "object" && !Array.isArray(x) && x !== null);
};
// https://stackoverflow.com/a/22482737/860099
function J(x) {
return x instanceof Object;
}
// https://stackoverflow.com/a/50712057/860099
function K(x)
{
let t= JSON.stringify(x);
return t ? t[0] === '{' : false;
}
// https://stackoverflow.com/a/13356338/860099
function L(x) {
return Object.prototype.toString.call(x) === "[object Object]";
};
// https://stackoverflow.com/a/46663081/860099
function M(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;
}
// https://stackoverflow.com/a/42250981/860099
function N(x) {
return $.type(x) === 'object';
}
// https://stackoverflow.com/a/34864175/860099
function O(x) {
if (Object.prototype.toString.call(x) !== '[object Object]') {
return false;
} else {
var prototype = Object.getPrototypeOf(x);
return prototype === null || prototype === Object.prototype;
}
}
// https://stackoverflow.com/a/57863169/860099
function P(x) {
while ( Object.prototype.toString.call(x) === '[object Object]')
if ((x = Object.getPrototypeOf(x)) === null)
return true
return false
}
// https://stackoverflow.com/a/43289971/860099
function Q(x){
try{
switch(x.constructor){
case Number:
case Function:
case Boolean:
case Symbol:
case Date:
case String:
case RegExp:
return x.constructor === Object;
case Error:
case EvalError:
case RangeError:
case ReferenceError:
case SyntaxError:
case TypeError:
case URIError:
return (Object === Error ? Error : x.constructor) === Object;
case Array:
case Int8Array:
case Uint8Array:
case Uint8ClampedArray:
case Int16Array:
case Uint16Array:
case Int32Array:
case Uint32Array:
case Float32Array:
case Float64Array:
return (Object === Array ? Array : x.constructor) === Object;
case Object:
default:
return (Object === Object ? Object : x.constructor) === Object;
}
} catch(ex){
return x == Object;
}
}
// https://stackoverflow.com/a/52478680/860099
function R(x) {
return typeof x == 'object' && x instanceof Object && !(x instanceof Array);
}
// https://stackoverflow.com/a/51458052/860099
function S(x)
{
return x != null && x.constructor?.name === "Object"
}
// https://stackoverflow.com/a/42250981/860099
function T(x) {
return x?.constructor?.toString().indexOf("Object") > -1;
}
// https://stackoverflow.com/a/43223661/860099
function U(x)
{
return x?.constructor === Object;
}
// https://stackoverflow.com/a/46663081/860099
function V(x) {
return x instanceof Object && x.constructor === Object;
}
// -------------
// TEST
// -------------
console.log('column: 1 2 3 4 5 6 - 7 8 9 10 11');
[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V]
.map(f=> console.log(`${f.name}: ${1*f(new Date())} ${1*f(/./)} ${1*f({})} ${1*f(Object.prototype)} ${1*f(Object.create(null))} ${1*f(()=>{})} - ${1*f("abc")} ${1*f(3)} ${1*f(true)} ${1*f(null)} ${1*f(undefined)}`))
console.log(`
Columns legend (test cases):
1: new Date()
2: /./ (RegExp)
3: {}
4: Object.prototype
5: Object.create(null)
6: ()=>{} (function)
7: "abc" (string)
8: 3 (number)
9: true (boolean)
10: null
11: undefined
Rows:
1 = is object
0 = is NOT object
Theoretically columns 1-6 should have have 1, columns 7-11 shoud have 0
`);
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"
integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww=="
crossorigin="anonymous"></script>
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome

- 85,173
- 29
- 368
- 345
Since there seems a lot of confusion about how to handle this problem correctly, I'll leave my 2 cents (this answer is spec compliant and produces correct results under all circumstances):
Testing for primitives:
undefined
null
boolean
string
number
function isPrimitive(o){return typeof o!=='object'||null}
An object is not a primitive:
function isObject(o){return !isPrimitive(o)}
Or alternatively:
function isObject(o){return o instanceof Object}
function isPrimitive(o){return !isObject(o)}
Testing for any Array:
const isArray=(function(){
const arrayTypes=Object.create(null);
arrayTypes['Array']=true;
arrayTypes['Int8Array']=true;
arrayTypes['Uint8Array']=true;
arrayTypes['Uint8ClampedArray']=true;
arrayTypes['Int16Array']=true;
arrayTypes['Uint16Array']=true;
arrayTypes['Int32Array']=true;
arrayTypes['Uint32Array']=true;
arrayTypes['BigInt64Array']=true;
arrayTypes['BigUint64Array']=true;
arrayTypes['Float32Array']=true;
arrayTypes['Float64Array']=true;
return function(o){
if (!o) return false;
return !isPrimitive(o)&&!!arrayTypes[o.constructor.name];
}
}());
Testing for object excluding: Date
RegExp
Boolean
Number
String
Function
any Array
const isObjectStrict=(function(){
const nativeTypes=Object.create(null);
nativeTypes['Date']=true;
nativeTypes['RegExp']=true;
nativeTypes['Boolean']=true;
nativeTypes['Number']=true;
nativeTypes['String']=true;
nativeTypes['Function']=true;
return function(o){
if (!o) return false;
return !isPrimitive(o)&&!isArray(o)&&!nativeTypes[o.constructor.name];
}
}());

- 274
- 2
- 6
After reading and trying out a lot of implementations, I've noticed that very few people try to check for values like JSON
, Math
, document
or objects with prototype chains longer than 1 step.
Instead of checking the typeof
of our variable and then hacking away edge-cases, I thought it'd be better if the check is kept as simple as possible to avoid having to refactor when there's new primitives or native objects added that register as typeof
of 'object'.
After all, the typeof
operator will tell you if something is an object to JavaScript, but JavaScript's definition of an object is too broad for most real-world scenarios (e.g. typeof null === 'object'
).
Below is a function that determines whether variable v
is an object by essentially repeating two checks:
- A loop is started that continues as long as the stringified version of
v
is'[object Object]'
.
I wanted the result of the function to be exactly like the logs below, so this is the only "objectness"-criteria I ended up with. If it fails, the function returns false right away. v
is replaced with the next prototype in the chain withv = Object.getPrototypeOf(v)
, but also directly evaluated after. When the new value ofv
isnull
, it means that every prototype including the root prototype (which could very well have been the only prototype inside the chain) have passed the check in the while loop and we can return true. Otherwise, a new iteration starts.
function isObj (v) {
while ( Object.prototype.toString.call(v) === '[object Object]')
if ((v = Object.getPrototypeOf(v)) === null)
return true
return false
}
console.log('FALSE:')
console.log('[] -> ', isObj([]))
console.log('null -> ', isObj(null))
console.log('document -> ', isObj(document))
console.log('JSON -> ', isObj(JSON))
console.log('function -> ', isObj(function () {}))
console.log('new Date() -> ', isObj(new Date()))
console.log('RegExp -> ', isObj(/./))
console.log('TRUE:')
console.log('{} -> ', isObj({}))
console.log('new Object() -> ', isObj(new Object()))
console.log('new Object(null) -> ', isObj(new Object(null)))
console.log('new Object({}) -> ', isObj(new Object({foo: 'bar'})))
console.log('Object.prototype -> ', isObj(Object.prototype))
console.log('Object.create(null) -> ', isObj(Object.create(null)))
console.log('Object.create({}) -> ', isObj(Object.create({foo: 'bar'})))
console.log('deep inheritance -> ', isObj(Object.create(Object.create({foo: 'bar'}))))

- 5,211
- 1
- 24
- 48
When everything else fails, I use this:
var isObject = function(item) {
return item.constructor.name === "Object";
};

- 131
- 1
- 1
-
2Why the string comparison, why not simply `item.constructor === Object`? – K3---rnc Feb 27 '16 at 23:20
-
`null` throws an exception `Uncaught 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 `indexOf` or because of `constructor.name`? – Jankapunkt Jan 24 '18 at 14:15
-
-
if your variable can't have falsy value `varName && varName.constructor.name === "Object"` if your variable may have falsy value varName != null && varName != undefined && varName.constructor.name === "Object" – Manoj Rana Mar 31 '22 at 08:09
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

- 11,711
- 6
- 48
- 69
-
2@SeregPie In future you should refrain from editing code in answers. As this answer stands, when testing I did obtain `null` as the result for the final test rather than `false`. See [When should I make edits to code?](https://meta.stackoverflow.com/questions/260245/when-should-i-make-edits-to-code) – Nick is tired Dec 13 '17 at 11:36
For the purpose of my code I found out this decision which corresponds with some of the answers above:
ES6 variant:
const checkType = o => Object.prototype
.toString
.call(o)
.replace(/\[|object\s|\]/g, '')
.toLowerCase();
ES5 variant:
function checkType(o){
return Object.prototype
.toString
.call(o)
.replace(/\[|object\s|\]/g, '')
.toLowerCase();
}
You can use it very simply:
checkType([]) === 'array'; // true
checkType({}) === 'object'; // true
checkType(1) === 'number'; // true
checkType('') === 'string'; // true
checkType({}.p) === 'undefined'; // true
checkType(null) === 'null'; // true
and so on..

- 485
- 5
- 5
-
1alternatively `slice(8, -1)` could be used instead of `replace(/\[|object\s|\]/g, '')`. It runs horribly faster. – toraman Feb 03 '22 at 03:03
-
1
const isObject = function(obj) {
const type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
!!obj
is shorthand for checking if obj
is truthy (to filter out null
)

- 5,211
- 1
- 24
- 48

- 734
- 10
- 7
if(typeof value === 'object' && value.constructor === Object)
{
console.log("This is an object");
}

- 1,286
- 1
- 16
- 13
-
And of course it will be `false` for the object `Object.assign({}, {constructor: null})`. – Sebastian Simon May 14 '20 at 18:17
It is an old question but thought to leave this here. Most people are checking if the variable is {}
meaning a key-value paired and not what is the underline construct that JavaScript is using for a given thing, cuz to be honest mostly everything in JavaScript is an object. So taking that out of the way. If you do...
let x = function() {}
typeof x === 'function' //true
x === Object(x) // true
x = []
x === Object(x) // true
// also
x = null
typeof null // 'object'
Most of the time what we want is to know if we have a resource object from an API or our database call returned from the ORM. We can then test if is not an Array
, is not null
, is not typeof 'function'
, and is an Object
// To account also for new Date() as @toddmo pointed out
x instanceof Object && x.constructor === Object
x = 'test' // false
x = 3 // false
x = 45.6 // false
x = undefiend // false
x = 'undefiend' // false
x = null // false
x = function(){} // false
x = [1, 2] // false
x = new Date() // false
x = {} // true

- 4,521
- 6
- 36
- 51
-
-
1@toddmo thanks for pointing that out. Now the example code returns false for `new Date()` – redeemefy Jan 02 '20 at 01:47
function isObjectLike(value) {
return value != null && typeof value == 'object' && !Array.isArray(value);
}
Based from lodash

- 5,353
- 1
- 38
- 35
-
2This solution will return true for arrays as @Exception pointed out below. Adding `&& !Array.isArray(value)` to the return statement would eliminate that – Matti Aug 28 '20 at 15:53
If explicitly want to check if the given value is {}
.
function isObject (value) {
return value && typeof value === 'object' && value.constructor === Object;
}

- 7,593
- 30
- 104
- 210
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 07:49
-
However, you can use `instanceof` to check for objects. Still, this is not an exact science. – Inanc Gumus May 10 '17 at 07:53
-
@inanc, well that is because `new Foo()` returns a `Foo` object, same as `new String()` returns a `String` object, or `new Date()` returns a `Date` object, you can do `Foo = function(){}; isVarTypeOf(new Foo(), Foo);` also – am05mhz May 12 '17 at 02: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 05: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 06:47
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

- 1,185
- 11
- 21
you can just use JSON.stringify
to test your Object, like this:
var test = {}
if(JSON.stringify(test)[0] === '{') {
console.log('this is a Object')
}

- 309
- 3
- 8
-
Might also want to handle _undefined_. `JSON.stringify(undefined)` will throw an exception. We use this: `function isObject(o) { try { return JSON.stringify(o)[0] === '{' } catch(ex) { return false } }` We have not measured it for performance, however. – storsoc Mar 20 '20 at 18:40
-
This fails for arrays and it fails for every object with a custom `toJSON` method, like `Date`s or the object `{ toJSON(){ return 1; } }`. – Sebastian Simon May 14 '20 at 18:21
-
+1 for creativity - this is quite nice and exotic alternative for other answers - this version handle more cases: `function isObject(x) {let t= JSON.stringify(x); return t ? t[0] === '{' : false;}` – Kamil Kiełczewski Sep 24 '20 at 11:23
-
I had this same idea upon reading the question, but looked for and found your answer before posting. Sometimes, this is indeed what people mean by "object". Other times, it is not. This answer is a worthy inclusion here. – Lonnie Best Mar 18 '22 at 22:30
-
Consider - typeof bar === "object"
to determine if bar
is an object
Although typeof bar === "object"
is a reliable way of checking if bar is an object, the surprising gotcha in JavaScript is that null is also considered an object!
Therefore, the following code will, to the surprise of most developers, log true (not false) to the console:
var bar = null;
console.log(typeof bar === "object"); // logs true!
As long as one is aware of this, the problem can easily be avoided by also checking if bar is null:
console.log((bar !== null) && (typeof bar === "object")); // logs false
To be entirely thorough in our answer, there are two other things worth noting:
First, the above solution will return false if bar is a function. In most cases, this is the desired behavior, but in situations where you want to also return true for functions, you could amend the above solution to be:
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function")));
Second, the above solution will return true if bar is an array (e.g., if var bar = [];
). In most cases, this is the desired behavior, since arrays are indeed objects, but in situations where you want to also false for arrays, you could amend the above solution to be:
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]"));
However, there’s one other alternative that returns false for nulls, arrays, and functions, but true for objects:
console.log((bar !== null) && (bar.constructor === Object));
Or, if you’re using jQuery:
console.log((bar !== null) && (typeof bar === "object") && (! $.isArray(bar)));
ES5 makes the array case quite simple, including its own null check:
console.log(Array.isArray(bar));

- 789
- 4
- 18
We can check this with only a single line, here obj can be any value (including null)
obj?.__proto__ === Object.prototype
or
obj?.constructor.name === 'Object';

- 67
- 5
Different approach via adverse selection:
I reviewed all answers here and am still missing a different approach. According to MDN docs, objects in JavaScript are non-primitive values. Primitive values:
- Boolean type
- Null type
- Undefined type
- Number type
- BigInt type
- String type
- Symbol type
Based on this fact, the following approach is practising an adverse selection:
// Check if value is primitive value according to MDN docs:
function isPrimitiveValue(value) {
return (
typeof value === "symbol" ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean" ||
typeof value === "undefined" ||
value === null ||
typeof value === "bigint"
);
};
// Check if input is not primitive value, therefore object:
function isObject(input) {
if (isPrimitiveValue(input)) {
return false;
}
return true;
};
console.log(isObject(10)); // false
console.log(isObject([{foo: "bar"}])); // true
console.log(isObject({ a: 1, b: 2, c: 3 })); // true
console.log(isObject(Object.getPrototypeOf("foo"))); // true
console.log(isObject(Symbol("foo"))); // false
console.log(isObject(BigInt(9007199254740991))); // false
console.log(isObject(null)); // false
console.log(isObject(undefined)); // false
console.log(isObject(false)); // false
console.log(isObject({})); // true

- 183
- 7
-
This works until the spec is changed and they add a new primitive type like when they added symbol in ES6 and bigint in ES2019. – PHP Guru Feb 17 '23 at 18:31
-
this was my solution to the problem in the end. Not foolproof but works for 99% of cases. – ejectamenta Mar 21 '23 at 14:38
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(...)

- 2,357
- 4
- 25
- 46
-
Was using this in AngularJS for a while, until this surprised us: angular.isObject(new Date()) // true – storsoc Mar 20 '20 at 18:30
The simplest way to determine if a variable is an Object or not:
first: Evaluate the type of Object
second: Getting an Array property from an Object must returns undefined
(For example length
is an Array property which does not work on Object)
so:
if (_object instanceof Object && _object.length === undefined) {
// here you can be sure that you have a curly bracket object :)
}

- 503
- 5
- 14
This is tricky because an array is an object type, a function is an object type and the actual object {} is also object type
Problem
const arr = []
const fun = function(){}
const actualObj = {}
arr instanceof Object // true
fun instanceof Object // true
actualObj instanceof Object // true
So the goal is actualObj must return true and everything else must return false
actualObj instanceof Object && !(actualObj instanceof Array) && !(typeof actualObj === 'function') // true

- 5,463
- 3
- 33
- 43
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>

- 9,880
- 3
- 65
- 77
Simple working solution:
function isObject(value) {
return !(value instanceof Date) && !Array.isArray(value) && !Object.is(value, null) && !Object.is(value, undefined) && !(value instanceof Function)
}

- 742
- 10
- 13
I think the reason there are so many answers is that lots of things are object
in javascript whether you like it or not.
You can iterate over "keys" of an array just like any other object...
var key,
arr = ['one', 'two', 'three'];
for (key in arr)
console.log(`${key}=${arr[key]}`);
console.log(arr[1]);
console.log(arr['1']);
// 0=one
// 1=two
// 2=three
// two
// two
Array is special (like many objects) in that it has some properties/methods that a generic Object
does not have (e.g. length
, forEach
, etc).
So really this question should be: How do I filter to specific types of objects?
After all, I could easily implement my own array or regex or symbol, it would also be an object but probably pass through all the various "is it a real object?" tests....because it IS a real object.
So you want to filter to certain types of javascript objects...
The best way is to just do feature testing. Do you care if it has a length
property for instance? Example: A NodeList
in the browser looks like an array and can be iterated like an array, but is not an array.
Anyway, if you just want to filter out specific types of objects, only you can define what you want to filter. Do you want to filter out RegExp? Date? Array? Browser DOM objects? Only you can decide what your filter chain looks like. You can use a fall-through switch to build your filter compactly.
function typeOfIs(val, type) {
return typeof val == type;
}
function constructorIs(val, constructor) {
return val && constructor && val.constructor === constructor;
}
function isObject(val) {
// catch the easy non-object values
if (!typeOfIs(val, 'object'))
return false;
// catch the cases you don't want to consider to be
// "real" objects for your use-case
switch (true) {
case val === null:
case Array.isArray(val):
case typeOfIs(val, 'function'):
case constructorIs(val, RegExp):
return false;
default:
return true;
}
}
function test(val) {
console.log(Object.prototype.toString.call(val)+': '+isObject(val));
}
test(undefined);
test(null);
test(function () {});
test(Symbol('foo'));
test(1);
test(true);
test(false);
test('hello world');
test([]);
test(/.*/g);
test(new Date()); // true (because we didn't filter for it)
test({}); // true
feature testing
A better thing though would probably be to ask WHY you want to filter and maybe just test if the properties/functions you need/expect are present on a given variable...if they are present, work with the variable and don't worry about whether it is some type of object or another. If they aren't present, then just throw an API error that you were passed some value that was not of the right type (ie missing the expected properties/functions).
e.g.
if (typeof someVariable.hasOwnProperty == 'function')
// ...

- 2,504
- 19
- 17
I am penning this answer because it is an entirely different approach to any of the other 50+ answers here due to the specific definition of "object".
This is for a library intended for public use, and this "object" will be provided by a user as an argument to class methods. The code also uses that externally created object to store additional properties, as a convenience. Requiring that the object be extensible doesn't strike me as a hardship on the user, and it allows me to use this simple, clean method for validating the user object, without typeof
, instanceof
or string comparisons of any kind. The object can be Array
, Promise
, any extensible type because it doesn't matter, so long as the object has the properties I require to be set and I can assign a value to additional properties.
Here's my isObject
function:
function isObject(o) {
try {
o._ = 1;
return (o._ === 1); // return false if you want to rely on strict mode throwing
} catch(e) {
return false;
}
}
You can set any property name and any value except undefined
. If you don't like the lingering test property you can do this:
function isObject(o) {
try {
o._ = 1;
const val = (o._ === 1); // ditto re: strict mode
delete o._;
return val;
} catch(e) {
return false;
}
}

- 601
- 7
- 12
use typeof(my_obj)
will tells which type of variable it is.
for Array:
Array.isArray(inp)
or [] isinstanceof Array
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]))
}
}

- 18,813
- 10
- 112
- 118
-
-
OP asked variable is object.. if you want to check is array, then try Array.isArray(inp) or [] isinstanceof Array – Mohideen bin Mohammed Apr 26 '19 at 09:52
-
2
-
1typeof (just like instanceof) is actually an *operator*, so no parenthesis are required. The correct syntax is "typeof x" since it's a "type operator". Just like you would do "instanceof x" and not instanceof(x). The code in the answer does run, however. – Netside Jul 12 '20 at 22:06
Remember guys that typeof new Date()
is "object"
.
So if you're looking for { key: value }
objects, a date object is invalid.
Finally then: o => o && typeof o === 'object' && !(o instanceof Date)
is a better answer to your question in my opinion.

- 949
- 6
- 7
isObject() checks whether passed argument is a object or not, using optional chaining and latest standards:
const isObject = (value) => {
return value?.constructor === Object;
}

- 99
- 1
- 4
-
This will fail for *many* objects, including arrays or custom ones like `class Foo {}; isObject(new Foo())`. It *sort of* checks for plain objects but it also will have false negatives for `Object.create(null)`. – VLAZ Jan 31 '23 at 20:16
Objects in JavaScript include arrays, functions, regular expressions, and more. Anything that is not a primitive in JavaScript is an object.
My solution tests the use of the in
operator which is only supported by objects. Trying to use in
with a primitive will throw an error.
From MDN:
in operator
The in operator returns true if the specified property is in the specified object or its prototype chain.
Exceptions
TypeError
Thrown if object is not an object (i.e. a primitive).
This function is concise, works without fail, and unlike the other answers here handles edge cases like document.all
successfully. Tested and works in old browsers (ES3 and up).
function isObject(obj) {
try {
// Test obj with in operator
return 0 in obj || true;
}
catch (e) {
// obj is an object unless e is a TypeError
return e.constructor!=TypeError;
}
}
If you don't want the overhead of a function and a try/catch this conditional statement also works:
if (typeof obj in{"function":1,object:1,undefined:1} && obj!==null && obj!==void 0) {
// obj is an object. Remember that functions and document.all are objects too.
}

- 1,301
- 11
- 20
A little NodeJS console experiment based on the reading of Matt Fenwick's third option to his complete answer above. Just a little tweak to get true
or false
.
The following return false for the object test.
> if(Object.getPrototypeOf('v') === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(1) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(false) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(['apple']) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
The object will return true.
> if(Object.getPrototypeOf({'this':10}) === Object.prototype){console.log(true);}else{console.log(false);}
true
undefined

- 37
- 2
- 10
var isArray=function(value){
if(Array.isArray){
return Array.isArray(value);
}else{
return Object.prototype.toString.call(value)==='[object Array]';
}
}
var isObject=function(value){
return value !== null&&!isArray(value) && typeof value === 'object';
}
var _val=new Date;
console.log(isObject(_val));//true
console.log(Object.prototype.toString.call(_val)==='[object Object]');//false

- 57
- 3
You can do this easily with toString() method of Object.prototype
if(Object.prototype.toString.call(variable) == "[object Object]"){
doSomething();
}
or
if(Object.prototype.toString.call(variable).slice(8,-1).toLowerCase() == "object"){
doSomething();
}

- 671
- 1
- 6
- 22
-
1You meant to write `slice(1, 7)` instead of `slice(8,1)`? You might want to elaborate a bit on the differences of these two methods, e. g. the last one also accepting null, Number, Array and the first one only accepting 'pure' objects (e.g. it does not accept `new Number()` even though that returns an object, too). – le_m Jul 12 '16 at 22:42
-
1
-
3
I have a code snippet that works. I find it confusing when the whole piece of code is not given, so I just created it myself:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunc()">Try it</button>
<script>
var abc = new Number();
// var abc = 4;
//this is a code variation which will give a diff alert
function myFunc()
{
if(abc && typeof abc === "object")
alert('abc is an object and does not return null value');
else
alert('abc is not an object');
}
</script>
</body>
</html>

- 12,111
- 21
- 91
- 136

- 7
- 1