George Reith
George Reith

Reputation: 13476

Force an object to evaluate to false

I'm guessing this is probably application specific however I am using node.js - as long as it works in the v8 engine, I don't mind.

I'm trying to create an Object that evaluates to false, for example:

var Foo = function() { return this; }
var bar = new Foo;
if (bar) // returns false;

Is this possible by overriding a certain function of the object, e.g. toString?

In case anyone is wondering what use case this may have: it is for returning error objects from functions that normally return a boolean value, but could also possibly have encountered an error and returned my custom error object.

I want any following conditionals to act as if the function returned a false value without having to modify the conditionals to accommodate for the possibility of a non boolean value.

Upvotes: 5

Views: 1291

Answers (1)

Esailija
Esailija

Reputation: 140236

The closest you can get is like

if (+obj)

Where a falsy object defines a .valueOf() function that returns 0 or false:

var o = {
    valueOf: function() {
        return false;
    }
};
if (+o) {
    throw unreachable();
}

Upvotes: 5

Related Questions