Game Development Reference
In-Depth Information
Here you declare five different variables that you can now use in your program. When you declare
these variables, they don't yet contain a value. In this case, these variables are considered
undefined . You can assign a value to a variable by using an assignment instruction . For example,
let's assign a value to the variable red , as follows:
red = 3;
The assignment instruction consists of the following parts:
The name of the variable that should be assigned a value
= sign
The new value of the variable
The
A semicolon
You can recognize the assignment instruction by the equals sign in the middle. However, it's better
to think of this sign as “becomes” rather than “equals” in JavaScript. After all, the variable isn't
yet equal to the value to the right of the equals sign—it becomes that value after the instruction is
executed. The syntax diagram describing the assignment instruction is given in Figure 3-1 .
instruction
variable
=
expression
;
Figure 3-1. Syntax diagram of an assignment instruction
So now you have seen one instruction for declaring a variable, and another instruction to store a
value in it. But if you already know which value you want to store in a variable when you declare it,
you can combine the declaration of a variable and the first assignment to it:
var red = 3;
When this instruction is executed, the memory will contain the value 3, as shown in Figure 3-2 .
red
3
Figure 3-2. Memory after a declaration and assignment of a variable
Here are a few examples of more declarations and assignments of numeric variables:
var age = 16;
var numberOfBananas;
numberOfBananas = 2;
var a, b;
a = 4;
var c = 4, d = 15, e = -3;
c = d;
numberOfBananas = age + 12;
 
 
Search WWH ::




Custom Search