DekGenius.com
[ Team LiB ] Previous Section Next Section

4.1 Creating a JavaScript Variable

NN 2, IE 3

4.1.1 Problem

You want to create a JavaScript variable value either in the global space or privately within a function.

4.1.2 Solution

Use the var keyword to define the first instance of every variable, whether you assign a value to the variable immediately or delay the assignment until later. Any variable defined outside of a function is part of the global variable scope:

var myVar = someValue;

All script statements on the page, including those inside functions, have read/write access to a global variable.

When you define a variable with var inside a function, only statements inside the function can access that variable:

function myFunction( ) {
    var myFuncVar = someValue;
    ...
}

Statements outside of the function cannot reach the value of a variable whose scope is limited to its containing function.

4.1.3 Discussion

A JavaScript variable has no inherent limit to the amount of data it can hold. Maximum capacity is determined strictly by memory available to the browser application—information not accessible to your scripts.

Variable scope is an important concept to understand in JavaScript. Not only is a global variable accessible by all script statements in the current window or frame, but statements in other frames or windows (served from the same domain and server) can access those global variables by way of the window or frame reference. For example, a statement in a menu frame can reference a global variable named myVar in a frame named content as follows:

parent.content.myVar

You don't have to worry about the same global variable names colliding when they exist in other windows or frames, because the references to those variables will always be different.

Where you must exercise care is in defining a new variable inside a function with the var keyword. If you fail to use the keyword inside the function, the variable is treated as a global variable. If you have defined a global variable with the same name, the function's assignment statement overwrites the value originally assigned to the global variable. The safest way to avoid these kinds of problems is to always use the var keyword with the first instance of any variable, regardless of where it's located in your scripts. Even though the keyword is optional for global variable declarations, it is good coding style to use var for globals as well. That way you can readily see where a variable is first used in a script.

Although some programming languages distinguish between the tasks of declaring a variable (essentially reserving memory space for its value) and initializing a variable (stuffing a value into it), JavaScript's dynamic memory allocation for variable values unburdens the scripter of memory concerns. A variable is truly variable in JavaScript in that not only can the value stored in the variable change with later reassignments of values, but even the data type of the variable's value can change (not that this is necessarily good programming practice, but that's simply a by-product of JavaScript's loose data typing).

Speaking of good programming practice, it is generally advisable to define global variables near the top of the script, just as it's also advisable to define heavily used variables inside a function at the top of the function. Even if you don't have a value ready to assign to the variable, you can simply declare the variable as undefined with a statement like the following:

var myVar;

If you have multiple variables that you'd like to declare, you may do so compactly by separating the variable names with commas:

var myVar, counter, fred, i, j;

You may even combine declarations and initializations in a comma-delimited statement:

var myVar, counter = 0, fred, i, j;

In examples throughout this book, you typically find variables being declared or initialized at the top of their scope regions, but not always. It's not unusual to find variables that are about to be used inside a for loop defined (with their var keywords) just before the loop statements. For example, if a nested pair of loops is in the offing, I may define the loop counter variables prior to the outer loop's start:

var i, j;
for (i = 0; i < array1.length; i++) {
    for (j = 0; j < array1[i].array2.length; j++) {
        ...
    }
}

This is merely my style preference. But in any case, this situation definitely calls for declaring the variables outside of the loops for another reason. If you were to use the var keywords in the loop counter initialization statements (e.g., var j = 0;), the nested loop would repeatedly invoke the var declaration keyword each time the outer loop executes. Internally, the JavaScript interpreter creates a new variable space for each var keyword. Fortunately, the interpreter is also able to keep track of which variable repeatedly declared is the current one, but it places an unnecessary burden on resources. Declare once, then initialize and reassign values as often as needed. Thus, in complex functions that have two or more outer for loops, you should declare the counter variable at the top of the function, and simply initialize the value at the start of each loop.

As for selecting the names for your variables, there are some explicit rules and implicit customs to follow. The explicit rules are more important. A variable name cannot:

  • Begin with a numeral

  • Contain any spaces or other whitespace characters

  • Contain punctuation or symbols except the underscore character

  • Be surrounded by quote marks

  • Be a reserved ECMAScript keyword (see Appendix C)

Conventions among programmers with respect to devising names for variables are not rigid, nor do they affect the operation of your scripts. They do, however, help in readability and maintenance when it comes time to remember what your script does six months from now.

The main idea behind a variable name is to help you identify what kind of value the variable contains (in fact, names are commonly called identifiers). Littering your scripts with a bunch of one- or two-letter variables won't help you track values or logic when reading the script. On the other hand, there are performance reasons (see Recipe 4.8) to keep names from getting outrageously long. The shorter the better, but not to the point of cryptic ciphers. If you need two or more words to describe the value, join the words together via underscore characters, or capitalize the first character of any words after the first word (a convention used throughout this book). Thus, either of the variable names in the following initializations are fine:

var teamMember = "George";
var team_member = "George";

Apply these rules and concepts to the identifiers you assign to element name and id attributes, as well. Your scripts will then have no trouble using these identifiers in DOM object references.

Variable names are case-sensitive. Therefore, it is permissible (although not necessarily advisable) to reuse an identifier with different case letters to carry different values. One convention that you might employ is to determine which variables won't be changing their values during the execution of your scripts (i.e., you will treat them as constants) and make their names all uppercase. Netscape 6 and later implement a forthcoming ECMAScript keyword called const, which you use in place of var to define a true constant value. No other browser supports this keyword yet, so you can use variables as constants and keep modification statements away from them.

JavaScript assigns data to a variable both "by reference" and "by value," depending on the type of data. If the data is a true object of any kind (e.g., DOM object, array, custom object), the variable contains a "live" reference to the object. You may then use that variable as a substitute reference to the object:

var elem = document.getElementById("myTable");
var padWidth = elem.cellPadding;

But if the data is a simple value (string, number, Boolean), the variable holds only a copy of the value, with no connection to the object from which the value came. Therefore, the padWidth variable shown above simply holds a string value; if you were to assign a new value to the variable, it would have no impact on the table element. To set the object's property, go back to the object reference and assign a value to the property:

elem.cellPadding = "10";

If an object's property value is itself another object, the variable receives that data as an object reference, still connected to its object:

var elem = document.getElementById("myTable");
var elemStyle = elem.style;
elemStyle.fontSize = "18px";

Exercise care with DOM objects assigned to variables. It may seem as though the variable is a mere copy of the object reference, but changes you make to the variable value affect the document node tree.

4.1.4 See Also

Chapter 1, Chapter 2, and Chapter 3 discuss assigning values of different types—strings, numbers, arrays, and objects—to variables; Recipe 4.8 for the impact of variable name length on performance.

    [ Team LiB ] Previous Section Next Section