Game Development Reference
In-Depth Information
Comparison Operators
The condition in the header of an if instruction is an expression that returns a truth value: yes or no .
When the outcome of the expression is yes , the body of the if instruction is executed. In these
conditions, you're allowed to use comparison operators. The following operators are available:
<
Less than
<=
Less than or equal to
>
Greater than
>=
Greater than or equal to
===
Equal to
!==
Not equal to
These operators may be used between any two numbers. On the left side and the right side of
these operators, you may put constant values, variables, or complete expressions with addition,
multiplication, or whatever you want. You test the equality of two values using a triple equals sign
( === ). This is very different from a single equals sign, which denotes an assignment. The difference
between these two operators is very important:
x = 5; means: assign the value 5 to x .
x === 5 means: is x equal to 5?
Because you have seen single-equals and triple-equals operators, you might wonder if there is also
a double-equals operator. There is. The double-equals operator also compares values, but if those
values aren't of the same type, this operator converts one of the values such that the types match.
Such a conversion sounds like it could be useful, but it leads to some strange behavior. Here are a
few examples:
'' == '0' // false
0 == '' // true!
0 == '0' // true!
The triple-equals operator would return false in all three cases because the types are different.
Generally, it's best to avoid the double-equals operator. The triple-equals operator is much more
predictable, which leads to fewer bugs and errors when you use it in your program.
Caution Chances are, you'll encounter the double-equals operator quite often in existing JavaScript
libraries or code snippets. Programming habits are hard to change.
 
 
Search WWH ::




Custom Search