tags:

views:

142

answers:

5

Is there any way to make an object return false in javascript?

var obj = new Object();

console.log(!!obj) // prints "true" even if it's empty
+4  A: 

No. But null will convert to false.

> typeof(null)
"object"
> null instanceof Object
false
> !!null
false

To see if the object contains any properties, use (shamelessly copied from http://stackoverflow.com/questions/1345939/how-do-i-count-javascript-objects-attributes):

function isEmpty (obj) {
    for (var k in obj) 
       if (obj.hasOwnProperty(k))
           return false;
    return true;
}
KennyTM
to clarify things: `null` is a primitive value of type 'Null' and not an object; it's just that `typeof` is somewhat broken
Christoph
+2  A: 

A null "object" (really value) will return false.

var obj = null;

console.log(!!obj);

If you wanted to check if it has no properties, you might try:

var obj = new Object();
var empty = true;
for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
       empty = false;
       break;
    }
}
console.log(empty);
tvanfosson
+2  A: 

I think that with the first ! you are casting obj to a boolean and negating its value- resulting in true if obj is null - , and with the second ! negating it again.

Pekka
No, the first `!` casts the object to boolean *then* negate it. The second `!` negates it *again* making the end result equivalent to casting the object to boolean. The asker has no problems in that statement.
KennyTM
Of course, thanks for the correction. Edited.
Pekka
+5  A: 

No. An object that doesn't have any properties assigned is not considered "empty".

The fact that a variable holds an instance of an object is enough to cause javascript to treat the variable as having the value of true when an expression requires a boolean value.

Edit

There are clearly some nuances to be cleared up looking at the other answers here.

null is not an object, it is the distinct lack of an object. The question refers to an Object, that is one that has just been created.

AnthonyWJones
+2  A: 

No.

Not sure why you'd want this, but there is a way you could do something like this but it's kinda hacky...

var obj = {
    toString: function() { return ''; }
};

alert(!! (''+obj));
Jani Hartikainen