6

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...?

3
  • {} is a new object. So abc !== "a new object" because abc is another object Commented Jun 17, 2011 at 6:38
  • I want to match: Is "abc" a blank hash map. Commented Jun 17, 2011 at 6:40
  • 1
    @Ikke I think this is not a duplicate of that one. Here we have an interesting point about an empty object. Commented Jun 17, 2011 at 6:49

4 Answers 4

4

{} 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

Sign up to request clarification or add additional context in comments.

3 Comments

How does checking the typeof abc help with knowing if it is an empty object?
@nnnnnn please see update and other answers testing for properties in the object
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 {} :).
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;
}

Comments

0
var abc = {};

this create an object

so you can try the type of:

if (typeof abc == "object")...

Comments

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'.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.