Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 940
George Reith Avatar asked Aug 11 '13 19:08

George Reith


1 Answers

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();
}
like image 52
Esailija Avatar answered Sep 20 '22 22:09

Esailija