user10712073
user10712073

Reputation:

falsy expressions with double equals

Why does the following code:

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

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

Upvotes: 1

Views: 88

Answers (2)

Takit Isy
Takit Isy

Reputation: 10091

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”

Upvotes: 1

Pointy
Pointy

Reputation: 414036

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.

Upvotes: 2

Related Questions