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...?
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...?
{} 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
typeof abc help with knowing if it is an empty 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 {} :).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'.