1

If I set a variable like this:

var a = {};

Check if it has any contents

var b = { x: 1 }

Check if it has any contents

var c = { y: null }

I think the test (a) will not work as it is not null. So how can I check if it has some contents if I do not know in advance what the contents are? In this case I want variables b and c to show up as having contents.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103

5 Answers5

1
function isEmpty(input)
{
    var result = true;


    for(item in input)
        result = false;

    return result;
}
John
  • 5,942
  • 3
  • 42
  • 79
1

A little wordy, but this should work:

var hasProperties = false;
for(var prop in obj) {
    hasProperties = true;
    break;
}
Allen G
  • 1,160
  • 6
  • 8
  • And for inhertied enumerable properties? – RobG Jun 04 '14 at 03:20
  • Inherited enumerable properties should be detected using this, which as I assume, is favorable behaviour for the OP. Though, according to the scenario of "if I set a variable like var a = {...}," inheritance should not be an issue. – Allen G Jun 04 '14 at 03:38
  • I guess it highlights the futility of a general purpose "is plain object" test, they all only work within a limited set of criteria. In the above, extending *Object.prototype* with an enumerable properties means that all objects "have contents". – RobG Jun 04 '14 at 08:40
0

Below is a piece of code what jQuery does:

// ...
isEmptyObject: function( obj ) {
    var name;
    for ( name in obj ) {
        return false;
    }
    return true;
},
// ...
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Try if(Object.keys(a).length).

Kamrul
  • 7,175
  • 3
  • 31
  • 31
0

Lots of answers, but I guess you want to check for own properties of the object:

for (var p in obj) {
  if (obj.hasOwnProperty(p)) {
    // obj has at least one enumerable own property
  }
}

But note that in ES5, objects can be constructed with non–enumerable own properties:

function hasEnumerableOwnProperties(obj) {
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) return true;
  }
  return false;
}

var obj = {}

Object.defineProperty(obj, 'foo', {enumerable:false, value:'foo'})

console.log(hasEnumerableOwnProperties(obj) + ':' + obj.foo); // false:foo

Javascript isn't designed to suit this kind of analysis, it's much better if you're after a particular property, feature or attribute to test for it specifically (i.e. use feature detection).

Don't try to infer some general behaviour based on a simple (often inconclusive) test (duck typing).

RobG
  • 142,382
  • 31
  • 172
  • 209