-1

This is something that I've always wondered. According to MDN, in JavaScript "The if statement executes a statement if a specified condition is true". So then why does this pass the statement?

var a = 7;
if( a ) {
    alert('true');
} else {
    alert('false');
}

The variable is neither true nor false, so why does it alert "true" instead of just skipping the entire if statement?

somebodysomewhere
  • 1,102
  • 1
  • 13
  • 25

5 Answers5

4

"is true" means "an expression that evaluates to a true value" not "is exactly equal to the boolean object true".

The formal language can be found in the specification.

Let exprRef be the result of evaluating Expression.
If ToBoolean(GetValue(exprRef)) is true, then
Return the result of evaluating the first Statement.
Else,
Return the result of evaluating the second Statement.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

In Javascript following values are always falsy:

false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)

All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.

If you want to compare with true without type conversion try a === true.

Kunal Kapadia
  • 3,223
  • 2
  • 28
  • 36
0

In JavaScript if(var) evaluates not just for boolean, but also for defined/initialized or non defined variables.

For example, if a var is undefined or null in that case if evaluates them to false

Aragorn
  • 5,021
  • 5
  • 26
  • 37
0

As stated by other before, it's performing a boolean test on the variable. Boolean values are binary; that's to say, the only possible values are 0 and 1, where true = 1, and false = 0.

The value you hard-coded into the if-statement is 7 = 0111, and all it takes is one of those numbers being a '1' to make it pass the test.

It work the same way with letters, except the if statement will convert letters from ASCII to binary: "A" = 0100 0001 (registered as 65 in ASCII. http://www.asciitable.com/) On the other hand, no input will return a false statement.

-2

In a computer, everything is a number. Boolean too, and usually are just one bit: 0 or 1.

But computer use more than one bit to store data, so Boolean are more than 0 or 1, but also 255, 42, or 25, while still having to pass a simple test.

So by convention, 0 is false, and any other value is true.

DrakaSAN
  • 7,673
  • 7
  • 52
  • 94