Game Development Reference
In-Depth Information
Priority of Operators
When multiple operators are used in an expression, the regular arithmetic rules of precedence apply:
multiplication before addition. The result of the expression 1+2*3 therefore is 7, not 9. Addition and
subtraction have the same priority, and multiplication and division as well.
If an expression contains multiple operators of the same priority, then the expression is computed
from left to right. So, the result of 10-5-2 is 3, not 7. When you want to deviate from these standard
precedence rules, you can use parentheses: for example, (1+2)*3 and 3+(6-5) . In practice, such
expressions generally also contain variables; otherwise you could calculate the results (9 and 4) yourself.
Using more parentheses than needed isn't forbidden: for example, 1+(2*3) . You can go completely
crazy with this if you want: ((1)+(((2)*3))) . However, your program will be much harder to read
if you do.
In summary, an expression can be a constant value (such as 12), it can be a variable, it can be
another expression in parentheses, or it can be an expression followed by an operator followed by
another expression. Figure 3-5 shows the (partial) syntax diagram representing an expression.
expression
constant
variable
expression
operator
expression
(
expression
)
Figure 3-5. Partial syntax diagram of an expression
Assigning a Function to a Variable
In JavaScript, functions (groups of instructions) are stored in memory. And as such, functions
themselves are also expressions. So, it's possible to assign a function to a variable. For example:
var someFunction = function () {
// do something
}
This example declares a variable someFunction and assigns it a value. The value this variable refers
to is an anonymous function . If you want to execute the instructions contained in this function,
you can call it by using the variable name, as follows:
someFunction();
 
 
Search WWH ::




Custom Search