Lukas Lukas - 1 year ago 61
Javascript Question

toBoolean method similar like toString

Is there a way to define a method on an

in JavaScript that acts like
just for booleans? Example (es6):

class MyClass {
toBoolean() {
return === bar;

so I can do something like this

const myClass = new MyClass();
if (myClass === true) baz();

sounds crazy to me, but I'm gonna ask nonetheless.

Answer Source

Apart from the fact that it would be a can of worms as drewmoore pointed out, it's not possible to do it in JavaScript at all.

There is no feature to "hook type conversion" in a way like overloading the cast operator in C++.

The reason why toString appears to do something similar is just because many functions implicitly try calling toString on your objects, and the JavaScript interpreter also does this when you try to concatenate something to a string using + but === doesn't do anything like that - in fact, the "selling point" of === is that it does no type conversion.

So there is no way to magically convert it to a boolean for comparison like this. One would still have to use if(myClass.toBoolean() === true), and then it would make more sense to name the method by what it actually does, e.g. if(myClass.isValid()) or whatever.