5

Possible Duplicates:
Object comparison in JavaScript
How do I test for an empty Javascript object from JSON?

var abc = {};
console.log(abc=={}) //false, why?

Why is it false? How do I match a blank hash map...?

Community
  • 1
  • 1
TIMEX
  • 217,272
  • 324
  • 727
  • 1,038

4 Answers4

3

{} is a new object instantiation. So abc !== "a new object" because abc is another object.

This test works:

var abc = {};
var abcd = {
  "no": "I am not empty"
}

function isEmpty(obj) {
  for (var o in obj)
    if (o) return false;
  return true;
}

console.log("abc is empty? " + isEmpty(abc))
console.log("abcd is empty? " + isEmpty(abcd))

Update: Just now saw that several others suggested the same, but using hasOwnProperty

I could not verify a difference in IE8 and Fx4 between mine and theirs but would love to be enlightened

mplungjan
  • 134,906
  • 25
  • 152
  • 209
  • 1
    How does checking the `typeof abc` help with knowing if it is an empty object? – nnnnnn Jun 17 '11 at 06:53
  • @nnnnnn please see update and other answers testing for properties in the object – mplungjan Jun 17 '11 at 07:59
  • `hasOwnProperty` is needed to differentiate between properties inherited from the prototype chain (which should not make the object "not empty"), and own properties. When you write a function, you might not want to use it only on `{}` :). – kapa Jun 17 '11 at 09:16
1
if (abc.toSource() === "({})")  // then `a` is empty

OR

function isEmpty(abc) {
    for(var prop in abc) {
        if(abc.hasOwnProperty(prop))
            return false;
    }
    return true;
}
Ravi Parekh
  • 3,038
  • 8
  • 34
  • 47
0
var abc = {};

this create an object

so you can try the type of:

if (typeof abc == "object")...
Ibu
  • 39,552
  • 10
  • 71
  • 99
0

The statement var abc = {}; creates a new (empty) object and points the variable abc to that object.

The test abc == {} creates a second new (empty) object and checks whether abc points to the same object. Which it doesn't, hence the false.

There is no built-in method (that I know of) to determine whether an object is empty, but you can write your own short function to do it like this:

function isObjectEmpty(ob) {
   for (var prop in ob)
      if (ob.hasOwnProperty(prop))
         return false;

   return true;
}

(The hasOwnProperty() check is to ignore properties in the prototype chain not directly in the object.)

Note: the term 'object' is what you want to use, not 'hash map'.

nnnnnn
  • 138,378
  • 23
  • 180
  • 229