Java Reference
In-Depth Information
As with much of JavaScript code, you'll fi nd that variable names are case sensitive. For example,
myVariable is not the same as myvariable. You'll fi nd that this is a very easy way for errors to slip
into your code, even when you become an expert at JavaScript.
Also, you can't use certain names and characters for your variable names. Names you can't use are
called reserved words. Reserved words are words that JavaScript keeps for its own use (for example, the
word var or the word with). Certain characters are also forbidden in variable names: for example, the
ampersand (&) and the percent sign (%). You are allowed to use numbers in your variable names, but the
names must not begin with numbers. So 101myVariable is not okay, but myVariable101 is. Let's look
at some more examples.
Invalid names include:
with
99variables
my%Variable
theGood&theBad
Valid names include
myVariable99
myPercent_Variable
the_Good_and_the_Bad
You may wish to use a naming convention for your variables (for example, one that describes what sort
of data you plan to hold in the variable). You can notate your variables in lots of different ways — none
are right or wrong, but it's best to stick with one of them. One common method is Hungarian notation ,
where the beginning of each variable name is a three-letter identifi er indicating the data type. For
example, you may start integer variable names with int , fl oating-point variable names with flt , string
variable names with str , and so on. However, as long as the names you use make sense and are used
consistently, it really doesn't matter what convention you choose.
Creating Variables and Giving Them Values
Before you can use a variable, you should declare its existence to the computer using the var keyword.
This warns the computer that it needs to reserve some memory for your data to be stored in later. To
declare a new variable called myFirstVariable , write the following:
var myFirstVariable;
Note that the semicolon at the end of the line is not part of the variable name but instead is used to indi-
cate to JavaScript the end of a statement. This line is an example of a JavaScript statement.
Once declared, a variable can be used to store any type of data. As we mentioned earlier, many other
programming languages, called strongly typed languages, require you to declare not only the variable
but also the type of data, such as numbers or text, that will be stored. However, JavaScript is a weakly
typed language; you don't need to limit yourself to what type of data a variable can hold.
Search WWH ::




Custom Search