HTML and CSS Reference
In-Depth Information
3.2.4 Scope of Variables
Scope describes where a variable is visible, or where it can be used, within the program.
JavaScript variables are either of global or local scope. A global variable can be accessed
from any JavaScript script on a page, as shown in Example 3.6. The variables we have
created so far are global in scope.
It is often desirable to create variables that are private to a certain section of the pro-
gram, thus avoiding naming conflicts and accidentally changing a value in some other
part of the program. Private variables are called local variables. Local variables are cre-
ated when a variable is declared within a function. Local variables must be declared with
the keyword, var . They are accessible only from within the function from the time of
declaration to the end of the enclosing block, and they take precedence over any global
variable with the same name. (See Chapter 7, “Functions.”)
3.2.5 Concatenation and Variables
To concatenate variables and strings together on the same line, the + sign is used. The +
sign is an operator because it operates on the expression on either side of it (each called
an operand). Sometimes the + sign is a string operator and sometimes it is a numeric
operator when used for addition. Addition is performed when both of the operands are
numbers. In expressions involving numeric and string values with the + operator, Java-
Script converts numeric values to strings. For example, consider these statements:
var temp = "The temperature is " + 87;
// returns "The temperature is 87"
var message = 25 + " days till Christmas";
// returns "25 days till Christmas"
But, if both operands are numbers, then addition is performed:
var sum = 10 + 5; // sum is 15
EXAMPLE 3.7
<html>
<head><title>Concatenation</title></head>
<body>
<script type="text/javascript">
1
var x = 25;
2
var y = 5 + "10 years";
3
document.write( x + " cats" , "<br />");
4
document.write( "almost " + 25 , "<br />");
5
document.write( x + 4 , "<br />");
6
document.write( y , "<br />");
7
document.write( x
+
5 + " dogs" , "<br />");
8
document.write( " dogs"
+ x + 5 , "<br />");
</script>
 
 
 
Search WWH ::




Custom Search