ptf
ptf

Reputation: 3370

Make positive numbers evaluate to true and negative to false

I'm playing around in javascript and I am wondering if you could make all values greater than -1 evaluate to true and all values from -1 and down evaluate to false?

Right now 1 == true and everything else equals false if you write it like this:

var i = 0;
if (i) {...} // I want this to be true

i = 1;
if (i) {...} // This is the only thing that is true

EDIT: With evaluate I mean that I don't runt a comparison, e.g. 0 > -1. I want JavaScript to coerce the number into a boolean value.

Upvotes: 3

Views: 3411

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

No, you can't change that, because it's built into the way the JavaScript == operator coerces values between types.

If you have a loose equality expression (==) where one of the operands is a boolean (true or false) and the other is a number, the JavaScript engine will try to convert the boolean into a number and will compare the result. true converts to 1 if you try to convert it to a number, and so that's why 1 == true.

Upvotes: 1

Kita
Kita

Reputation: 2634

you mean this?

if ( i > -1 ) {
    ....
}

Upvotes: 1

Related Questions