Game Development Reference
In-Depth Information
In the fourth line of this example, you see that it's possible to declare multiple variables in one declaration.
You can even perform multiple declarations with assignments in a single declaration, as can be seen in
the sixth line of the example code. On the right side of the assignment, you can put other variables or
mathematical expressions, as you can see in the last two lines. The instruction c = d; results in the value
stored in variable d being stored in variable c as well. Because the variable d contains the value 15, after
this instruction is executed, the variable c also contains the value 15. The last instruction takes the
value stored in the variable age (16), adds 12 to it, and stores the result in the variable numberOfBananas
(which now has the value 28—a lot of bananas!). In summary, the memory looks something like what is
depicted in Figure 3-3 after these instructions have been executed.
age
16
a
4
c
15
e
-3
numberOfBananas
b
d
28
15
Figure 3-3. Overview of the memory after declaration and assignment of multiple variables
The syntax of declaring variables (with an optional initialization) is expressed in the diagram shown in
Figure 3-4 .
declaration
var
name
=
expression
;
,
Figure 3-4. Syntax diagram of variable declaration with an optional initialization
Global Variables and Strict Mode
Instead of declaring a variable before using it, it's also possible in JavaScript to simply start using
the variable without declaring it. For example, consider the following instructions:
var a = 3;
var b;
b = 4;
x = a + b;
As you can see, the variables a and b are declared in the first two instructions by using the var
keyword. The variable x is never declared, but it's used to store the sum of the two variables.
JavaScript allows this. However, this is very bad practice, and here is why. The problem with
simply using a variable without declaring it is that the JavaScript interpreter automatically declares
 
 
Search WWH ::




Custom Search