Section D. Variables


D. Variables

Variables are nothing more than useful containers to hold a value that's going to be used and/or changed in your script. In fact, every script uses variables to store and manipulate data, and anyone who has even the least bit of JavaScript experience will intuitively use them correctly.

Variable names

JavaScript variable names must consist of letters, numbers, underscores, and dollar signs. The first character may not be a number. Remember that JavaScript is case-sensitive: the variable test is not the same as the variable Test.

A custom in JavaScript development is to spell longer variable or function names in camelCase so that they're easier to read. The name starts with a lowercase character, but whenever a new "word" begins, you use an uppercase character. Sandwich Picker, for instance, uses the variable currentPrice instead of currentprice or current_price.

The W3C DOM uses the same system, for instance, getElementById or createElement. If you do the same with your variable names, you'll get comfortable with the system quickly, and lessen your chances of making mistakes with inner capitals.

Reserved Words

You may not use the following words as variable or function names, because they already mean something in JavaScript:

break, case, catch, continue, default, delete, do, else, false, finally, for, function, if, in, instanceof, new, null, return, switch, this, throw, true, try, typeof, var, void, while, with.

The following words are reserved for future extensions of JavaScript, such as the upcoming 2.0 specification:

abstract, boolean, byte, char, class, const, debugger, double, enum, export, extends, final, float, goto, implements, import, int, interface, long, native, package, private, protected, public, short, static, super, synchronized, throws, transient, volatile.

At the time of writing, Mozilla and Safari give an error if you use any of the above words as variable or function names, although Explorer and Opera allow them.


The var keyword

The first time I use a new variable, I precede its name by the keyword var. This is an explicit variable declaration: I take the time and trouble to explain that I am declaring a new variable.

You don't have to assign a value to the new variable:

var x; 


You have now explicitly declared variable x, but you haven't assigned it a value yet, and as we saw in 5B it now holds the special value undefined. That's allowed, but it's best to assign a value as soon as possible, since you generally don't want the undefined value to mess up your scripts.

Implicit variable declaration

Using the var keyword is not required. If you start using a variable in your program without declaring it, JavaScript shrugs and creates it. This is called implicit variable declaration. An implicitly declared variable is always global in scope (see below).

The following two examples are both correct JavaScript:

var x = 10; var a = x * 2; alert(a); // b has never been used yet b = x * 2; alert(b); 


I do not use var to declare the variable b, but since I assign a value to it, JavaScript creates it automatically. Nonetheless, explicitly declaring your variables keeps your scripts clear and avoids scope issues, so I advise you always to do it.

Variable scope

Every variable has a scope: an 'area' inside which the variable is known, but outside of which it's unreachable. There are two scopes: global and local.

A global variable is defined throughout the JavaScript code (or, more correctly, throughout one global object) and can be used anywhere. A local variable is defined in only one function.

No Block Scope

Note that JavaScript has no block scope, as C++ and Java do. Any local variable is known throughout the entire function in which it's defined.


Use local variables

It's good programming practice to use as many local variables as possible. This prevents variables from interfering with each other, even if they share a name.

For instance, in Sandwich Picker I use the variable price to hold the total price of all sandwiches the user ordered. After all, it's a glaringly obvious name for a variable that holds a price, and other programmers will immediately understand its purpose.

If I had more price-calculation functions, I'd likely want to use price there, too. However, if price were a global variable, several functions would change its value. The result could be that price has an unexpected value and my calculations would go wrong.

It's far safer to define each price variable separatelyto create one local variable price for each price-calculation function. Each function will be unaware of the price variables in the other functions, and there is no danger of interference.

Defining local variables

How do you define a local variable? There are two ways:

  • You explicitly declare them with the var keyword inside the body of a function.

  • You declare them as an argument when you define a function.

A variable that has been declared in any other way is global in scope. (We'll discuss functions in more depth in 5I.)

In the following example, message is a global variable, because it's defined outside of any function body:

var message = 'Error!'; function doSomething() {     alert(message); } 


In this example, it's a local variable, because it's defined in a function body:

function doSomething() {     var message = 'Error!';     alert(message); } 


In this example, it's global again. It's used in the function body, but it isn't declared by the var keyword:

function doSomething() {     message = 'Error!';     alert(message); } 


Here, finally, it's local again, because it's a function argument:

doSomething('Error!'); function doSomething(message) {     alert(message); } 




ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net