Game Development Reference
In-Depth Information
that variable for you without you realizing it. If you happen to use a variable with the same name
somewhere else, your program may display behavior you don't expect because that variable already
exists. In addition, if you use a lot of different variables, you have to keep track of these global
variables as well. But an even bigger problem is shown in the following example:
var myDaughtersAge = 12;
var myAge = 36;
var ourAgeDifference = myAge - mydaughtersAge;
When programming these instructions, you would expect that the variable ourAgeDifference will
contain the value 24 (36 minus 12). However, in reality it will be undefined . The reason is that there is
a typo in the third instruction. The variable name shouldn't be mydaughtersAge , but myDaughtersAge .
Instead of stopping the script and reporting an error, the browser/interpreter silently declares a
new global variable called mydaughtersAge . Because this variable is undefined (it doesn't refer
to a value yet), any calculations done with this variable will also be undefined. So, the variable
ourAgeDifference is then undefined as well.
These kinds of problems are really hard to solve. Fortunately, the new EMCAScript 5 standard has
something called strict mode . When a script is interpreted in strict mode, it isn't allowed to use
variables without declaring them first. If you want a script to be interpreted in strict mode, the only
thing you have to do is add a single line at the beginning of the script, as follows:
"use strict";
var myDaughtersAge = 12;
var myAge = 36;
var ourAgeDifference = myAge - mydaughtersAge;
The string/instruction "use strict"; tells the interpreter that the script should be interpreted in strict
mode. If you now try to run this script, the browser will stop the script and report the error that a
variable is being used without having been declared.
In addition to checking whether a variable is declared before use, strict mode includes a couple
of other things that make writing correct JavaScript code easier. Furthermore, it's likely that newer
versions of the JavaScript standard will be close to the JavaScript syntax restrictions imposed by
strict mode.
I highly recommend that you write all your JavaScript code in strict mode. To set the model, all the
remaining examples in this topic are programmed in strict mode. It saves programmers a lot of
headaches, and the code is readier for future versions of JavaScript.
Instructions and Expressions
If you look at the elements in the syntax diagrams, you probably notice that the value or program
fragment on the right side of an assignment is called an expression . So what is the difference
between an expression and an instruction ? The difference between the two is that an instruction
changes the memory in some way, whereas an expression has a value. Examples of instructions
 
Search WWH ::




Custom Search