Take advantage of user-defined variables in JavaScript

Learn how to master variables, the special information-holding areas that are crucial to a programming language

Programming languages are next to useless without variables. These special information-holding areas can store numbers, text strings, objects, and other data types. Once stored, this information can be used later in your program. With a variable, a person's name could be stored and used at some point in the script.

Variables are temporary holders of information. They can hold:

  • Numeric values ("numbers") -- numbers that can be added together. Example: 2+2 results in 4
  • Character strings -- a collection of text, such as "JavaScript" or "My name is Mudd"
  • True/false values -- the Boolean true and false
  • Objects -- JavaScript or user-defined objects (JavaScript variables can hold a few other kinds of data, but these are by far the most common types)

(Note: As with most modern programming languages, JavaScript supports array variables in addition to the basic scalar variables used to hold the above data types. We'll concentrate on single-value variables for this column and devote a separate column to arrays.)

JavaScript variables "belong" to the script document that created them; the variables are lost when the document is unloaded. In addition, the contents of a variable are erased when you assign a new value to them. Though a variable created in one document script is not usually seen by another document script, JavaScript does provide ways to share variables between scripts. You do this by referencing the name of the document along with the name of the variable.

Several JavaScript instructions create and store variables, but the basic way to accomplish this manually is with the equals (=) assignment operator. The basic syntax is:

VariableName = value

The first argument is the name of the variable. Variable names can be very long, but you are restricted in the characters you may use. For more information on valid variable names, see the section on Variable name limits.

The second argument is the contents of the variable. You can put all sorts of stuff into a variable, including a number, a string, a math expression (such as 2+2), and various other things that we'll get to in a bit.

Pascal users may be tempted to construct the variable assignment using :=. Be aware that this syntax is not supported in JavaScript.

Following is a more specific rundown of the four most common contents you can place in JavaScript variables, including examples.

Contents placed in JavaScript variables

Numbers in variables

A number is one or more digits stored in the computer in such a way that JavaScript can perform math calculations with them. JavaScript supports both integers and floating-point values. To place a number in a variable, just provide the variable name, the equals sign (the variable assignment operator), and the value you want to use. For example, the following is what you do to place the number 10 in a variable named MyVar:

MyVar = 10;

Strings in variables

A string is one or more text characters arranged in memory in single file. Strings can contain numbers (digits), letters, punctuation, or a combination of these elements. Math calculations cannot be performed on strings. Strings are assigned to JavaScript variables by being enclosed in a set of single or double quotes:

"I am a string"

or

'I am a string'

Note that double or single quotes are acceptable; unlike some languages, such as Perl, JavaScript makes no distinction between the two forms of quote marks. This working example shows how to place a string into a variable:

MyVar = "This is JavaScript";

Boolean values in variables

There are two Boolean values: true and false. Some programming languages don't have a separate set of Boolean values, and instead use 0 for false, and 1 or -1 (or any other non-zero value) for true. JavaScript can use these numbers to represent true and false but, in addition, reserves the words "true" and "false" to mean Boolean true and false. You can think of the Boolean true and false values as being equivalent to on/off or yes/no. To assign a Boolean value to a variable, provide just the word true or false, without quotes. Here's an example:

MyVar = true;

Objects in variables

Variables can contain objects, including JavaScript objects. There are basically two kinds of object variables:

  • Variables that contain built-in browser-related objects -- window, document, navigator, and so on -- actually are references to the original object. They are like copies, but the copies change if the original changes. In some cases, making a change to the object in the variable affects the original JavaScript object.

  • Variables that contain user-defined objects represent the actual object. Make a change to the object in the variable, and you change only that object.

To assign a JavaScript object to a variable, provide the name of the object, as in:

MyVar = navigator;

To assign a new copy of a user-defined object to a variable, use the new statement, and provide the name of the object function:

MyVar = new myObject();

SUBHEAD Variable name limits

When it comes to the names you can give variables, JavaScript offers a great deal of latitude. JavaScript variables can be almost unlimited in length, although for practical reasons you'll probably keep your variable names under 10 or 15 characters. Shorter variable names help JavaScript execute the program faster. Keep the following in mind when naming your variables:

  • Variable names should consist of letters only -- without spaces. You can use numbers as long as the name doesn't start with a digit. For example, MyVar1 is acceptable, but 1MyVar is not.

  • Don't use punctuation characters in variable names. Exception: the underscore character ( _ ). That is, the variable My_Var is acceptable, but My*Var is not. Variables can begin with the underscore character.

  • Variable names are case-sensitive. The variable MyVar is a distinctly different variable from myVar, myvar, and other variations.

Understanding JavaScript's "loose" variable data types

Unlike some other programming languages, in JavaScript there is no need to explicitly define the type of variable you want to create. This JavaScript behavior is called "loose data typing," and it differs from C and Java, both of which use strict data typing.

In JavaScript there is no need to differentiate variable types by appending special characters to the end of the variable name, such as MyVar$ for a string variable (or, for that matter, $MyVar for a scalar variable, a la Perl). JavaScript internally decodes the variable type based on its content.

Using the var statement to assign a variable

JavaScript supports a var statement that can be used to explicitly define a variable. The syntax is merely the statement var, a space, and the same variable assignment expression detailed above. For instance:

var MyVar = "This is a variable";

You can also use the var statement with the variable name to declare the variable but not define a value for it:

var MyVar;

In this case, you've defined MyVar in memory but have yet to assign a value to it. This technique is often used when setting up global variables -- variables that can be freely shared anywhere in your script. For more information about global variables, see the section "Understanding the scope of variables", below.

String length limitations

JavaScript imposes a limit of 254 characters for each string variable assignment in your program. If you go over the 254-character limit, JavaScript responds with a "Unterminated string literal" error message. (Note: This is fundamentally a limit of JavaScript in Netscape 2.0x; it's a good idea to observe it since not all users have adopted Netscape 3.0.)

You can create longer strings by "piecing" them together -- as long as each piece is 254 characters or less. After assigning a string to each variable, you combine them using the + character. This is called "concatenation." The following example shows how concatenation works:

MyVar = "This is the start " + of how you " + " can build strings";

Each individual string segment -- defined by text within the quotes -- can be up to 254 characters. To make a string longer than 254 characters, merely add more segments. Another approach is to build strings using the += assignment operator, like this:

MyVar = "This is the start "
MyVar += "of how you "
MyVar + = can build strings "

You can continue to concatenate strings this way as long as your computer has the memory for it. But, while JavaScript can hold strings larger than that possible in many other programming languages (like Basic's typical 64K), doing so can severely degrade the performance of the system. Obviously, you won't create a lot of huge string variables. It's just nice to know that, if needed, a JavaScript variable can accommodate so much text.

Understanding the "scope" of variables

The "scope of a variable" has nothing to do with optics or mouthwash, but rather the extent to which a variable is visible to other parts of a JavaScript program. Unless you provide explicit instructions to tell JavaScript otherwise, the scope of its variables is managed as follows:

  • Variables defined outside a function are available to any function within the script, as long as all the variables are definined in the script of the same HTML document. These are referred to as global variables.

  • Variables defined inside a function are also global, assuming the var statement is not used when first declaring that variable. That is, MyVar = "hello."

  • Variables defined inside a function with the var statement are "local" to that function only. These are referred to as local variables.

  • Global variables remain in memory even after a script has stopped execution. The variable remains in memory until the document is unloaded.

Local variables are treated as if they don't exist outside the function where they are defined. That way, you can use the same variable name inside a function, and that variable won't interfere with the same-named variable elsewhere in the script.

Following is an example that demonstrates this. When you click the button, the script displays three alert boxes. The following details what happens when you click the button:

  • JavaScript calls firstFunction, which assigns a value of 1 to a local variable named MyVar. The contents of MyVar is displayed.

  • JavaScript calls secondFunction, which assigns a value of 2 to a local variable, also called MyVar. The contents of MyVar are displayed.

  • JavaScript returns to firstFunction, where the contents of MyVar are again displayed. The result is 1, which is the value of MyVar local to firstFunction.

Referencing variables in other loaded documents

When using frames, it is often necessary to share variables across documents. One or more frames may need a variable contained in another frame. By their nature, variables (even global ones) are not visible outside the document that created them. So, when you want to reference a variable in another document -- and assuming that document is loaded into the browser -- you need to explicitly reference that variable by adding the window name in front of the variable name. Here is syntax:

winname.varname

where winname is the name of the document, and varnameis the name of the variable. More about document names in a bit.

You can assign and reference variables using the following technique. For example, this sets the MyVar variable in the mydoc window to 1:

mydoc.MyVar = 1;

The code below assigns the value of a local MyVar variable in the mydoc window.

VarInThisDoc = mydoc.MyVar;

Where do the names for the windows come from? It all depends on how the windows are used.

To use a variable in the main browser window from a window that you created, first provide a "link" to the parent window object, using this method:

newwindow = window.open ("","NewWindow");  //repeat this for Mac/X Netscape 2.0
newwindow.creator = self;

Then, in this new window you can refer to any variable in the main window using the syntax:

creator.MyVar;

To use a variable in a window you've created, refer to it using the object name you've provided when you created the window. For instance, you'd use newwindow for a window created with the following:

newwindow = window.open ("","NewWindow");

Now refer to that variable using the syntax:

newwindow.MyVar;

To use a variable defined in the frameset -- that is, the document containing

tag -- refer to it as parent. Here's an example:

parent.MyVar;

To use a variable in another frame document, refer to it using the frame name you've provided in the

Gordon McCombis an author, consultant, and lecturer. He has written 50 books and over a thousand magazine articles during his 20 years as a professional writer. More than a million copies of his books are in print. Gordon also writes a weekly syndicated newspaper column on computers, reaching several million readers worldwide. Gordon's latest book is The JavaScript Sourcebook, available from Wiley Computer Publishing.

Learn more about this topic

This story, "Take advantage of user-defined variables in JavaScript" was originally published by JavaWorld.

Copyright © 1997 IDG Communications, Inc.