4

Is there a property from an object that I can modify to specify the truth value for the object. For example add a line inside:

var myObj{...}

so that I can determine whether the code block associated with the following if-statement is executed:

if(myObj){
    //dosomething
}

Something analogous in Python would be overriding the __bool__ method.

Juan Carlos Ramirez
  • 2,054
  • 1
  • 7
  • 22

3 Answers3

5

JavaScript does not have a mechanism to override operations like this. Objects will always be truthy as defined by the ECMAScript spec pointed out by Felix Kling. The closest that I can think of that does something similar to that is the toString() method; but there is no toBool() method that you can override.

I'm not super familiar with Python, but I'm pretty sure that __bool__ is basically a way to override how an Object is cast to a Boolean. I'm comparing that to similar language features like __lt__ which I would also assume is how Python allows you to override certain operators in similar to C++.

It's not directly related, but you should also consider reading this question: Overloading Arithmetic Operators in JavaScript?.

Consider also this excerpt from 2ality's Why all objects are truthy in JavaScript, emphasis mine:

The conversion to boolean is different for historic reasons: For ECMAScript 1, it was decided to not allow objects to configure that conversion. The rationale was as follows. The boolean operators || and && preserve the values of their operands. Therefore, the same object may have to be coerced several times. That was considered a performance problem and led to the rejection.

zero298
  • 25,467
  • 10
  • 75
  • 100
1

When you say if(myObj){...}in javascript. The condition will be true if myObj value is not one of undefined,null,0,false, zero length string values. so any value except this values makes the condition true in javascript.

behzad besharati
  • 5,873
  • 3
  • 18
  • 22
0

That doesn't exist in JavaScript, if you're defining a map then it doesn't make sense to have it behave as a boolean value.

For that you can either set a key inside that object to be a boolean:

let myObj = { isValid: true }

if (myObj.isValid) {
    // do something
}

or assign null to it in which case you can check for it's validity:

let myObj = null

if (myObj === null) {
    // do something
}

Also, it would be better practice to check the object against a real value instead of relying on the magic of truthy values as it may result in false result.

Samer
  • 973
  • 1
  • 6
  • 15