1

I have a question regarding javascript truthy / falsy

As far as I know, any non-zero number including negative numbers is truthy. But if this is the case then why

-1 == true //returns false

But also

-1 == false //returns false

Can someone shed some light? I would appreciate it.

Ovidiu
  • 157
  • 13
  • "truthy" doesn't mean "equal to true", just like "positive" doesn't mean "equal to +1". There are lots of truthy values and `true` is just one of them. – georg Feb 14 '18 at 13:20

4 Answers4

6

When using the == operator with a numeric operand and a boolean operand, the boolean operand is first converted to a number, and the result is compared with the numeric operand. That makes your statements the equivalent of:

-1 == Number(true)

and

-1 == Number(false)

Which in turn are

-1 == 1

and

-1 == 0

Which shows why you're always seeing a false result. If you force the conversion to happen to the numeric operand, you get the result you're after:

Boolean(-1) == true //true
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
1

No, a boolean is either 0 (false) or 1 (true) like a bit.

Here is an example:

console.log(0 == false); // returns true => 0 is equivalent to false
console.log(1 == true); // returns true => 1 is equivalent to true
console.log(-1 == false); // returns false => -1 is not equivalent to false
console.log(-1 == true); // returns false => -1 is not equivalent to true
ADreNaLiNe-DJ
  • 4,787
  • 3
  • 26
  • 35
1

Any non-zero number evaluates to true and zero evaluates to false. That is not the same as being equal to true/false.

Executing the code here below (and substituting -1 with different values) could help you understand this:

if (-1) {
    true;
} else {
    false;
}
Cheatah
  • 11
  • 3
0

In addition to the @James Thorpe answer, if you want to identify zero and non-zero numbers you can use the following code:

console.log(Math.abs(-1) > 0);
console.log(Math.abs(0) > 0);
console.log(Math.abs(1) > 0);
Pedram
  • 828
  • 9
  • 24