Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

Variable Declaration

Before you use a variable, you need to create it. JavaScript is a loosely typed language, so you do not have to explicitly specify the data type of a variable when you create it. As needed, data types are converted automatically during the course of the script execution.

There are two ways to create a variable. The first type of declaration includes the var keyword, followed by the name of the variable:

var variableName

When interpreting this statement, the browser creates a link between the name of the variable and its memory address, so successive references can be done by name. As opposed to most programming languages, declarations are not limited to a specific zone but can be done anywhere throughout the script.

The action of assigning an initial value to a variable is called initialization. You give the variable a value using the most common assignment operator—the equal sign:

var variableName = initialValue

You should only use the var keyword when you create the variable. When you want to refer to the variable, you only use its name. Assign a value to a variable (after it has been declared) in the following fashion:

variableName = anyValue

In conclusion, you use var only once per variable. A global variable can be created simply by assigning it a value without the var keyword. Local variables inside functions, on the other hand, must be declared with the var keyword. See Chapter 9, Functions and Variable Scope, for more details on local and global variables.

As in most programming languages, JavaScript allows you to declare numerous variables in the same statement, using a comma to separate them:

var variableName1 = initialValue1, variableName2 = initialValue2, ...

JavaScript Entities

JavaScript entities can be assigned to HTML attributes. This attribute substitution enables creation of more flexible HTML constructions, without the writing overhead of full JavaScript scripts. Note that JavaScript entities are not supported by Netscape Navigator 2.0x and Microsoft Internet Explorer 3.0x.

You are probably familiar with HTML character entities with which you can display a character by its numerical code or name. You precede a name or a number with an ampersand (&) and terminate it with a semicolon (;). Here are a few examples:

>
<
©

These HTML entities evaluate to the following characters:

> (greater than)
< (less than)
© (copyright)

JavaScript entities also start with an ampersand and end with a semicolon. Instead of a name (as in the first two examples) or a number (as in the third example), you use a JavaScript expression enclosed in curly braces ({ and }). Note that you can use JavaScript entities to assign HTML attributes only. Consider the following HTML document:

<HTML>
<HEAD>
<TITLE>JavaScript Entities</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide content from old browsers

var fontSize = "+4"
var fontColor = "red"

// end hiding content-->
</SCRIPT>
</HEAD>
<BODY>
<FONT COLOR="&{fontColor};" SIZE="&{fontSize};">
Flexible attributes with JavaScript entities
</FONT>
</BODY>
</HTML>

Example 5-1 (ex5-1.htm). JavaScript entities enable creation of flexible constructs.

The entity &{fontColor}; is replaced by the current value of fontColor and &{fontSize}; is replaced by the current value of fontSize. Since JavaScript can only use values that are stored in memory at the time of page layout, JavaScript entities should be used only after calling the script that assigns their value. Figure 5-1 shows the result of Example 5-1.

Once layout is complete, the display of the page can change only if you reload the page. Even if the value of the JavaScript entity variable changes, the entity itself does not change until you reload the page.

Unlike HTML character entities which can be used in any script statement, JavaScript entities can be used only in a tag statement. Another difference is that, while HTML character entities may substitute for any HTML element, JavaScript ones are limited to HTML attribute substitution only. For example, you cannot specify the entity “&{text};" with the variable text = "<H1>Hi!</H1>"—it is not a valid value for a tag attribute.

Type Conversion

As mentioned above, data types are converted automatically as needed during the course of script execution. A variable may hold a numeric value at one point of the script and a string at another one. The following statements constitute a valid JavaScript script:

var myVar = 12
myVar = "university"

The first statement assigns a numeric value to myVar, and the second one assigns it a string. Such conversions are not allowed in strictly typed languages such as C++ and Java and, in general, are not recommended in JavaScript either. You should normally assign an initial value to a variable according to its role and keep the same data type throughout the entire script.

Mixing Strings and Numbers

Mixing strings and numbers is sometimes necessary for certain operations. Since this “mixture” is tricky and can generate unexpected results, you should be familiar with its exact rules.

When an expression including both numbers and strings is evaluated to a single value, that value evaluates to a string. Converting it to a number is usually impossible. For example, the number 6 can be easily converted to a string (6), while the string “horse” cannot be converted to a number.

Another important rule is that the JavaScript interpreter evaluates expressions from left to right, and only parentheses can change the order of evaluation. Take a look at the following expressions, numbered by lines.

/* 1 */8 + 8 // 16
/* 2 */"8" + 8 // "88"
/* 3 */8 + "8" // "88"
/* 4 */"8" + "8" // "88"
/* 5 */8 + 8 + "8" // "168"
/* 6 */8 + "8" + 8 // "888"

All preceding expressions use the string concatenation operator which is also the numeric plus operator. (See Chapter 7, Utilizing JavaScript Operators, for more details.)

The first expression simply adds up two numbers using a numeric format. It uses the standard plus operator and evaluates to the sum of its operands. The second expression is quite different. Its first operand is a string rather than a number. In order to add a number to a string, the number is converted to its matching string and the strings are then concatenated. The third and fourth expressions are similar in that they also include at least one string operand. The fifth expression is a bit more tricky. The first two operands are added up because they are numbers. The expression now evaluates to 16 + "8" which, as you already know, evaluates to "168". Using parentheses can change the result. For example:

8 + (8 + "8") // "888"

In this expression the content in the parentheses is evaluated first to "88" and the entire expression evaluates to "888". Comparing the sixth expression to the fifth one clearly demonstrates what left-to-right evaluation means. The basic structure of an expression including both numeric and string values is shown in Figure 5-2.


Figure 5-2.  The general syntax of a mixed expression.

Whenever a string is found during the expression evaluation, the accumulated value thus far is converted to a string. The remaining numeric values on the right-hand side are automatically converted to strings when concatenated to this accumulated value.

If you want to convert a single number to a string, you can use one of the following three methods:

var newVar = "" + numericValue
var newVar = new String(numericValue)
var newVar = numericValue.toString()

The first method is simple. You use the concatenation operator, which instructs JavaScript to convert the number to a string and then append it to a null string. The other methods are discussed later in the book.

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us