Game Development Reference
In-Depth Information
In this case, if the expression isAlive evaluates to true , the body of the if instruction is executed.
You might think this code would generate a compiler error and you need to do a comparison of the
Boolean variable, like this:
if (isAlive === true)
// do something
However, this extra comparison isn't necessary. A conditional expression as in the if instruction
has to evaluate to true or false . Because a Boolean variable already represents one of these two
values, you don't need to perform the comparison. In fact, if the previous comparison was needed,
you would also need to compare that outcome again with a Boolean value:
if ((isAlive === true) === true)
// do something
And it gets worse:
if ((((((isAlive === true) === true) === true) === true) === true) === true)
// do something
In summary, don't make things more complicated than they are. If the outcome is already a Boolean
value, you don't have to compare it to anything.
You can use the Boolean type to store complex expressions that are either true or fa l se. Let's look
at a few additional examples:
var a = 12 > 5;
var b = a && 3 + 4 === 8;
var c = a || b;
if (!c)
a = false;
Before you read on, try to determine the value of the variables a , b , and c after these instructions have
been executed. In the first line, you declare and initialize a Boolean a . The truth value that is stored in this
Boolean is evaluated from the expression 12 > 5 , which evaluates to true . This value is then assigned to
variable a . In the second line, you declare and initialize a new variable b , in which you store the result of
a more complex expression. The first part of this expression is the variable a , which contains the value
true . The second part of the expression is a comparison expression 3 + 4 === 8 . This comparison is not
true (3 + 4 doesn't equal 8), so this evaluates to false , and therefore the logical and also results in false .
Therefore, the variable b contains the value false after this instruction executes.
The third instruction stores the result of the logical or operation on variables a and b in variable c .
Because a contains the value true , the outcome of this operation is also true , and this outcome
is assigned to c . Finally, there is an if instruction, which assigns the value false to variable a , but
only if !c evaluates to true . In this case, c is true , so !c is false , which means the body of the if
instruction is not executed. Therefore, after all the instructions are executed, a and c both contain
the value true , and b contains the value false .
Doing these kinds of exercises shows that it's very easy to make logical mistakes. This process is
similar to what you do when you debug your code. Step by step, you move through the instructions
and determine the values of the variables at various stages. A single mix-up can cause something
you assume to be true to evaluate to false !
Search WWH ::




Custom Search