1

Why does the following code:

var foo=10;
foo==true //false

return false? Shouldn´t be true, since any number is true?

  • 2
    Answered previously here: https://stackoverflow.com/a/12236341/1024832. The gist is that `true` converts to `1`. To coerce a number to a boolean, you can double-not it like this: `!!foo==true`. – Marc Nov 27 '18 at 14:25

2 Answers2

2

It's a matter of context. If foo is initialized as in your code

var foo = 10;

then

if (foo) alert("it's true!");

will fire the alert() because in that context the if test is just the value of the variable, which is the "truthy" value 10.

However, the comparison foo == true is a different context: it's the "abstract" equality operation. There, a comparison between a number and a boolean first forces the boolean to be converted to a number. That turns true into 1, by definition. Then the comparison is made, and 10 is clearly not equal to 1.

There's rarely a reason to explicitly compare expression values to true or false. If you want to see if a value is "truthy" (a value you know is numeric, but you don't know the exact value), you can get the same result that the if test would get with:

var isTruthy = !!foo;

That applies the ! boolean complement operator twice to the value of foo. The first application first converts 10 to true and then inverts that to false. The second application converts that false back to true, so the value of isTruthy will be true.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

In your comparison, true is turned into 1 because foo is a number.
Check this example snippet:

var foo = 10;
console.log("foo: " + foo);
console.log(foo==true);

var foo = 1;
console.log("foo: " + foo);
console.log(foo==true);

You may also want to learn about strict comparison, that will prevent a comparison between a number and a boolean to return a true value:

var foo = 1;
console.log("foo: " + foo);
console.log("Regular comparison: " + (foo==true));
console.log("Strict comparison: " + (foo===true));

Link to “Comparison_Operators”

halfer
  • 19,824
  • 17
  • 99
  • 186
Takit Isy
  • 9,688
  • 3
  • 23
  • 47