242

Assuming I declare

var ad = {}; 

How can I check whether this object will contain any user-defined properties?

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
Ricky
  • 34,377
  • 39
  • 91
  • 131

17 Answers17

409

You can use the built in Object.keys method to get a list of keys on an object and test its length.

var x = {};
// some code where value of x changes and than you want to check whether it is null or some object with values

if(Object.keys(x).length){
 // Your code here if x has some properties  
}
Dhaval Chaudhary
  • 5,428
  • 2
  • 24
  • 39
  • 31
    _This right here_ is the correct answer. The accepted answer above is a work-around and is more expensive than just checking the number of keys; this makes _way more sense_. – dudewad Feb 24 '17 at 20:05
  • 6
    Object.keys("mystring"); yields keys as well which I think is undesirable. This answer is incomplete in my opinion. – Mike de Klerk Sep 02 '17 at 17:15
  • 3
    @MikedeKlerk please read it carefully it's not Object.keys("mystring"); it's Object.keys(objectVariableName) which will return array of all the keys in object. ex : { 'x' : 'abc', 'y' : 'def' } it will be ['x' , 'y'] – Dhaval Chaudhary Sep 04 '17 at 08:59
  • 3
    @DhavalChaudhary Thanks for your reply to my comment. When I try this code `var str = "MyString"; Object.keys(str);`, the console outputs 8 keys, from 0 to 7, for each character. Or do I still not understand the answer. – Mike de Klerk Sep 04 '17 at 09:26
  • 9
    @MikedeKlerk but it's only solution for objects not for strings pls refer question. – Dhaval Chaudhary Sep 04 '17 at 10:22
  • 1
    what about this scenario? `Object.keys({[Symbol()]:1}).length` ? outputs 0. So the above answer is not always correct @dudewad – Meir Sep 16 '20 at 15:09
  • Yeah I think at the time I wrote that I was unaware of symbols and/or did not consider them as something to use as a key, though that's a primary use case of them. – dudewad Sep 16 '20 at 17:25
  • 1
    @MeilechWieder I think a combination of the Object.keys() approach and Object.getOwnPropertySymbols() would do best. So the check would become `if (Object.keys(x).length || Object.getOwnPropertySymbols(x).length) { ...` I didn't test that but it seems like it's a good place to start. I would wrap that in a utility method probably to make it less verbose when you need to do key length checks. – dudewad Sep 16 '20 at 17:27
  • @Meilech it is useful comment but JSON.stringify({foo:function(){}}) == '{}' returns true :( – portal TheAnGeLs Feb 11 '22 at 00:00
121

What about making a simple function?

function isEmptyObject(obj) {
  for(var prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
      return false;
    }
  }
  return true;
}

isEmptyObject({}); // true
isEmptyObject({foo:'bar'});  // false

The hasOwnProperty method call directly on the Object.prototype is only to add little more safety, imagine the following using a normal obj.hasOwnProperty(...) call:

isEmptyObject({hasOwnProperty:'boom'});  // false

Note: (for the future) The above method relies on the for...in statement, and this statement iterates only over enumerable properties, in the currently most widely implemented ECMAScript Standard (3rd edition) the programmer doesn't have any way to create non-enumerable properties.

However this has changed now with ECMAScript 5th Edition, and we are able to create non-enumerable, non-writable or non-deletable properties, so the above method can fail, e.g.:

var obj = {};
Object.defineProperty(obj, 'test', { value: 'testVal', 
  enumerable: false,
  writable: true,
  configurable: true
});
isEmptyObject(obj); // true, wrong!!
obj.hasOwnProperty('test'); // true, the property exist!!

An ECMAScript 5 solution to this problem would be:

function isEmptyObject(obj) {
  return Object.getOwnPropertyNames(obj).length === 0;
}

The Object.getOwnPropertyNames method returns an Array containing the names of all the own properties of an object, enumerable or not, this method is being implemented now by browser vendors, it's already on the Chrome 5 Beta and the latest WebKit Nightly Builds.

Object.defineProperty is also available on those browsers and latest Firefox 3.7 Alpha releases.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 1
    What is the advantage to Object.prototype.hasOwnProperty.call(obj, prop) over obj.hasOwnProperty(prop)? – Casey Chu Apr 20 '10 at 07:11
  • 3
    @Casey, edited, if an object overrides the `hasOwnProperty` property, the function might crash... I know I'm a little bit paranoid... but sometimes you don't know in which kind of environment your code will be used, but you know what method you want to use... – Christian C. Salvadó Apr 20 '10 at 07:13
  • 3
    +1 for answering this question... and other questions of the future! :) – Daniel Vassallo Apr 20 '10 at 07:49
  • 1
    Note there is also a bug in IE where if you have a property with a name that matches a non-enumerable property in `Object.prototype`, it doesn't get enumerated by `for...in`. So `isEmptyObject({toString:1})` will fail. This is one of the unfortunate reasons you can't *quite* use `Object` as a general-purpose mapping. – bobince Apr 20 '10 at 07:58
  • @bobnice, Oh yes, that [bug](https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug) is pretty serious, fortunately this is one of the ES-deviations that disappeared on IE9. – Christian C. Salvadó Apr 20 '10 at 16:02
  • It looks like `keys` [is faster than](http://jsperf.com/getownpropertynames-vs-keys) `getOwnPropertyNames` but I'm not sure I understand them enough to know if `keys` would be an acceptable substitute in this situation. – Michael Martin-Smucker Jan 13 '14 at 23:39
  • 1
    @MichaelMartin-Smucker— [*keys*](http://ecma-international.org/ecma-262/5.1/#sec-15.2.3.14) only returns enumerable own properties, so not suitable here. – RobG Jun 04 '14 at 03:53
  • 1
    @RobG - however, in the common case where programmer is using object as an associative array, so only *wants* enumerable properties, keys is suitable. In fact, often one deliberately wishes to exclude non-enumerable properties - they represent special functionality attached to an object, not "the logical contents" of the object - so excluding non-enumerables may be preferable in *most* use cases. `keys` is usually the more suitable approach, in my experience. – ToolmakerSteve Oct 12 '19 at 11:28
  • @ToolmakerSteve—sure, but in the context of the OP ("How can I check whether this object will contain any user-defined properties?") and the comment I was replying to (" if keys would be an acceptable substitute in this situation") then finding user defined, non–enumerable own properties may be important. – RobG Oct 13 '19 at 10:58
  • 1
    @RobG - I agree. Its good that you pointed out the situation with non-enumerables. Its also good for people to realize that keys are only "not suitable", *if* one wishes to include non-enumerables. It is likely that some, perhaps many, readers would not catch the distinction you were making. (And its unclear to me, whether "this situation" was intended to include non-enumerables or not; I don't assume OP's question should be taken literally, to definitely include non-enumerable own properties. The differences between alternatives should be made clear, not dismissed as "not suitable".) – ToolmakerSteve Oct 13 '19 at 14:34
98

You can loop over the properties of your object as follows:

for(var prop in ad) {
    if (ad.hasOwnProperty(prop)) {
        // handle prop as required
    }
}

It is important to use the hasOwnProperty() method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.

Edit

From the comments: You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment

auerbachb
  • 857
  • 11
  • 25
Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
  • 3
    Hi Daniel, actually I'm seeking a device to check whether an object contains user-defined properies or not. Not to check whether a specific property exist. – Ricky Apr 21 '10 at 02:40
  • 7
    @Ricky: You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment. – Daniel Vassallo Apr 21 '10 at 04:11
  • 13
    I think these days using `Object.keys` would be the easiest: `var a = [1,2,3];a.something=4;console.log(Object.keys(a))` Because it's already part of ECMA 5 you can safely shim it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Compatibility – HMR Nov 15 '13 at 13:32
  • 2
    Note that "these days" with ES5, native objects can have non–enumerable own properties, e.g. `Object.defineProperty(obj, 'foo', {enumerable:false, value:'foo'})`. – RobG Jun 04 '14 at 03:35
  • 2
    This solution is a way to _check for keys that exist_, but the true, efficient, and most-correct answer is below using Object.keys(x).length. You don't need to make your own function, one already exists! – dudewad Feb 24 '17 at 20:06
  • 2
    @dudewad - `Object.keys` is only *efficient* if browser doesn't create a new array. The performance test - added more recently than your comment - shows the function above is faster. OTOH I agree that using a built-in function is generally preferable to inventing one's own; in practice the performance difference probably doesn't matter. – ToolmakerSteve Oct 12 '19 at 11:45
61

With jQuery you can use:

$.isEmptyObject(obj); // Returns: Boolean

As of jQuery 1.4 this method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty).

With ECMAScript 5th Edition in modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

var obj = { blah: 1 };
var isEmpty = !Object.keys(obj).length;

Or plain old JavaScript:

var isEmpty = function(obj) {
               for(var p in obj){
                  return false;
               }
               return true;
            };
kayz1
  • 7,260
  • 3
  • 53
  • 56
46

Most recent browsers (and node.js) support Object.keys() which returns an array with all the keys in your object literal so you could do the following:

var ad = {}; 
Object.keys(ad).length;//this will be 0 in this case

Browser Support: Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Zaptree
  • 3,763
  • 1
  • 31
  • 26
15

If you're using underscore.js then you can use the _.isEmpty function:

var obj = {};
var emptyObject = _.isEmpty(obj);
Gruff Bunny
  • 27,738
  • 10
  • 72
  • 59
  • 1
    Just for anyone passing by, this is not a method dedicated to objects. `_.isEmpty([]) // true` Be sure to check first: http://stackoverflow.com/a/22482737/1922747 – djv Jan 02 '16 at 19:45
11

If you are willing to use lodash, you can use the some method.

_.some(obj) // returns true or false

See this small jsbin example

sfs
  • 431
  • 8
  • 16
  • var x = [1,2] // true – djv Dec 30 '15 at 18:51
  • @damionjn I added your code to the example. I see your point with the array returning the wrong answer, but OP initially declared a variable as an object so I believe its alright to assume this. There is an answer above which uses the underscores isEmpty method (lodash has the same method). That answer has the exact same issue. If you give isEmpty a non empty array you will also get the wrong result. – sfs Jan 01 '16 at 20:41
  • Fair enough, but we should be providing answers with all bases covered to be sure of best practices. You're right, I passed right by his answer without any criticism. Just for anyone passing by, this is not a method dedicated to objects. `_.some([1, 2]) // true` Be sure to check first: http://stackoverflow.com/a/13356338/1922747 – djv Jan 02 '16 at 19:42
6
for (var hasProperties in ad) break;
if (hasProperties)
    ... // ad has properties

If you have to be safe and check for Object prototypes (these are added by certain libraries and not there by default):

var hasProperties = false;
for (var x in ad) {
    if (ad.hasOwnProperty(x)) {
        hasProperties = true;
        break;
    }
}
if (hasProperties)
    ... // ad has properties
Casey Chu
  • 25,069
  • 10
  • 40
  • 59
  • 1
    in your solution there is no filtering for unwanted prototype properties, that means it might be misbehaving when using a library like Prototype.js or an unexperienced user added additional prototype properties to the object. Check out Daniels solution on this page. – Joscha Apr 20 '10 at 06:55
  • You don't have to use a library or be unexperienced to extend an object's prototype. _Some_ experienced programmers do this all the time. – Alsciende Apr 21 '10 at 08:15
2
for(var memberName in ad)
{
  //Member Name: memberName
  //Member Value: ad[memberName]
}

Member means Member property, member variable, whatever you want to call it >_>

The above code will return EVERYTHING, including toString... If you only want to see if the object's prototype has been extended:

var dummyObj = {};  
for(var memberName in ad)
{
  if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
  //Member Name: memberName
  //Member Value: ad[memberName]

}

Note A: We check to see if the dummy object's member has the same type as our testing object's member. If it is an extend, dummyobject's member type should be "undefined"

Warty
  • 7,237
  • 1
  • 31
  • 49
  • Hi, can I just know whether an object contain properties or not? Thanks – Ricky Apr 20 '10 at 06:50
  • in your solution there is no filtering for unwanted prototype properties, that means it might be misbehaving when using a library like Prototype.js or an unexperienced user added additional prototype properties to the object. – Joscha Apr 20 '10 at 06:51
  • check out Daniels solution on this page - its less error-prone! – Joscha Apr 20 '10 at 06:52
  • 2
    Your first code block does not cover it at all. the second code block misbehaves if I add a variable to the "ad" object which is undefined. Really, check out Daniels answer, it's the only correct one and fast, as it uses a native implementation called "hasOwnProperty". – Joscha Apr 20 '10 at 06:54
  • @Ricky: If you want to check whether an object contains properties, you can simply use the example in my answer: http://stackoverflow.com/questions/2673121/javascript-how-to-check-an-object-without-any-properties/2673141#2673141. If the code reaches the comment, your object would not have any direct properties. If not, it would. – Daniel Vassallo Apr 20 '10 at 06:59
  • If someone extended the `Object.prototype` with something, e.g. `Object.prototype.foo = "foo";`, the property will be resolvable in both objects, `dummyObj['foo'] === ad['foo'];` the `typeof` check doesn't helps much – Christian C. Salvadó Apr 20 '10 at 07:49
2
var hasAnyProps = false; for (var key in obj) { hasAnyProps = true; break; }
// as of this line hasAnyProps will show Boolean whether or not any iterable props exist

Simple, works in every browser, and even though it's technically a loop for all keys on the object it does NOT loop through them all...either there's 0 and the loop doesn't run or there is some and it breaks after the first one (because all we're checking is if there's ANY...so why continue?)

Jimbo Jonny
  • 3,549
  • 1
  • 19
  • 23
2

ES6 function

/**
 * Returns true if an object is empty.
 * @param  {*} obj the object to test
 * @return {boolean} returns true if object is empty, otherwise returns false
 */
const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0

Examples:


let obj = "this is an object with String constructor"
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = {}
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = []
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = [{prop:"value"}]
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = {prop:"value"}
console.log(pureObjectIsEmpty(obj)) // empty? false

Sébastien
  • 1,749
  • 1
  • 15
  • 19
1

You can use the following:

Double bang !! property lookup

var a = !![]; // true
var a = !!null; // false

hasOwnProperty This is something that I used to use:

var myObject = {
  name: 'John',
  address: null
};
if (myObject.hasOwnProperty('address')) { // true
  // do something if it exists.
}

However, JavaScript decided not to protect the method’s name, so it could be tampered with.

var myObject = {
  hasOwnProperty: 'I will populate it myself!'
};

prop in myObject

var myObject = {
  name: 'John',
  address: null,
  developer: false
};
'developer' in myObject; // true, remember it's looking for exists, not value.

typeof

if (typeof myObject.name !== 'undefined') {
  // do something
}

However, it doesn't check for null.

I think this is the best way.

in operator

var myObject = {
  name: 'John',
  address: null
};

if('name' in myObject) {
  console.log("Name exists in myObject");
}else{
  console.log("Name does not exist in myObject");
}

result:

Name exists in myObject

Here is a link that goes into more detail on the in operator: Determining if an object property exists

James Drinkard
  • 15,342
  • 16
  • 114
  • 137
1

Very late answer, but this is how you could handle it with prototypes.

Array.prototype.Any = function(func) {
    return this.some(func || function(x) { return x });
}

Object.prototype.IsAny = function() {
    return Object.keys(this).Any();
}
ProfiT
  • 11
  • 2
1

When sure that the object is a user-defined one, the easiest way to determine if UDO is empty, would be the following code:

isEmpty=
/*b.b Troy III p.a.e*/
function(x,p){for(p in x)return!1;return!0};

Even though this method is (by nature) a deductive one, - it's the quickest, and fastest possible.

a={};
isEmpty(a) >> true

a.b=1
isEmpty(a) >> false 

p.s.: !don't use it on browser-defined objects.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0

Object.hasOwn is a new static method (not fully supported by all browsers yet) which checks if the specified object has the indicated property as his own property and return true if that is the case. It will return false if the property is either inherited or does not exist on that object.

You can iterate through the object properties and check if they are indeed own properties

for (let property in ad) {
   if (Object.hasOwn(ad, property)) {
    // handle your code for object own properties here
  }
}   

More about Object.hasOwn - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/

Browser compatibility here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
0

I'm not sure if this is a good approach but I use this condition to check if an object has or hasn't any property. Could be easily transformed into a function.

const obj = {};
    
if(function(){for (key in obj){return true}return false}())
{
  //do something;
}
else
{
  //do something else;
}
    
//Condition could be shorted by e.g. function(){for(key in obj){return 1}return 0}()
-4

How about this?

var obj = {},
var isEmpty = !obj;
var hasContent = !!obj
  • This answer doesn't answer the question. OP is asking if an object contains user-defined properties - your answer checks if the object itself will convert to a Boolean false value. – Jasmonate Oct 25 '19 at 05:51
  • ...and I also realized later that James already included this option in his answer. Sorry guys. – Peter Toth Oct 25 '19 at 23:55