As before, for a full list of all the supported operators, refer to the online JavaScript documentation.. Basic JavaScript ProgrammingBasic JavaScript Programming To tie together all the
Trang 1Basic Commands and Language Structure
Variable names (and function names) can consist of the letters a through z, the numbers 0
through 9, and the underscore (_) symbol A variable name cannot start with a number
Tip
If you declare a variable inside a function, you can access the contents of that variable only
from inside the function itself This is said to be the scope of the variable On the other
hand, if you declare a variable inside a <script> block outside your functions, you can
access the contents of that variable from any JavaScript code on the web page This is
referred to as global scope
Operators and Expressions
After you define a variable, you can work with its contents or alter them using operators Table 12.2 lists some of the more popular operators provided by JavaScript and examples of each (As before, for a full list of all the supported operators, refer to the online JavaScript documentation.)
Table 12.2 JavaScript Operators and Expressions Operator Example Description
+ a = b + c Adds variables b and c and assigns the result to variable a
- a = b - c Subtracts the value of variable c from variable b and assigns the result to
variable a
* a = b * c Multiplies variable b by variable c and assigns the result to variable a
/ a = b / c Divides variable b by variable c and assigns the result to variable a
% a = b % c Obtains the modulus of variable b when it's divided by variable c, and assigns
the result to variable a (Note: A modulus is a function that returns the
remainder.)
++ a = ++b Increments variable b by 1 and assigns the result to variable a
a = b Decrements variable b by 1 and assigns the result to variable a
Note
The examples shown in the second column of Table 12.2 are called expressions An
expression is any valid set of variables, operators, and other expressions that evaluate to a
single value For example, b + c evaluates to a single value, which is assigned to a
file:///G|/1/0672328860/ch12lev1sec3.html (7 von 8) [19.12.2006 13:49:30]
Trang 2You also can use a special set of operators, called assignment operators, that combine the assignment
function (=) and an operator into a single function Table 12.3 lists the assignment operators provided
by JavaScript
Table 12.3 JavaScript Assignment Operators Assignment Operator Example Description
+= a += b This example is equivalent to the statement a = a + b
-= a -= b This example is equivalent to the statement a = a - b
*= a *= b This example is equivalent to the statement a = a * b
/= a /= b This example is equivalent to the statement a = a / b
/= a %= b This example is equivalent to the statement a = a % b
Note
The + and += operators can be used with string variables as well as numeric variables
When you use them with strings, the result of a = "text" + " and more text" is a variable
containing "text and more text"
Trang 3Basic JavaScript Programming
Basic JavaScript Programming
To tie together all the event handlers, methods, parameters, functions, variables, and operators,
JavaScript includes a simple set of programming statements that are similar to those provided in most other programming languages
If you have any programming experience at all, spending a few minutes browsing the list of supported statements discussed in Netscape's online documentation will set you well on your way toward creating your first JavaScript programs If you don't have the experience, the following section includes a quick crash course in basic programming
What Is a Script?
Regardless of which programming language you use, a script is simply a set of instructions that
describes some action, or group of actions, that you want the computer to perform In the most basic case, a script starts at the beginning of a list of code and works through each instruction in the list one
at a time until it reaches the end, as follows:
<script language="JavaScript">
// Start of program - NOTE: lines that start with '//' are treated as comments
document.write("step one") ;
document.write("step two") ;
// End of program
</script>
However, you'll rarely ever want a script to proceed straight through a list of stepsespecially in
JavaScriptbecause writing the messages on the screen using HTML would be easier than coding them with JavaScript For this reason, most scripting languages include a basic set of statements that enable you to control the flow of execution
The if Statement
The first instruction that enables you to control the flow is the if statement It enables you to create blocks of code that will be executed only if a particular condition is satisfied For example, if you have a web form that asks whether a person is male or female, you might want to respond to the person using
a gender-specific response:
if (form.theSex.value == "male") {
document.write("Thank you for your response, Sir" ) ;
}
if (form.theSex.value == "female") {
document.write("Thank you for your response, Madam" ) ;
}
If this piece of code is run and the property form.theSex.value is assigned a value of "male", the first
document.write() method is called If it's assigned a value of "female", the second statement is
displayed The block of code next to the if statement performs a comparison between the property form.
file:///G|/1/0672328860/ch12lev1sec4.html (1 von 5) [19.12.2006 13:49:31]
Trang 4theSex.value and the word "male" This comparison is made using comparison operators In this case, a test for equivalence was performed, as signified by the == symbol Table 12.4 lists the comparison
operators currently recognized by JavaScript
Table 12.4 JavaScript Comparison Operators
<= Less than or equal to -a <= b tests to see whether a is less than or equal to b
>= Greater than or equal to -a >= b tests to see whether a is greater than or equal to b
The if else Statement
You also can write the preceding example using a different version of the if statement that incorporates
an else statement:
if (form.theSex.value == "male") {
document.write("Thank you for your response, Sir") ;
}
else {
document.write("Thank you for your response, Madam") ;
}
In this example, you don't need a second if testa person can be only male or femaleso you use the else
statement to tell the program to display the second message if the first test fails
Note
In both the preceding examples, any number of statements could be assigned to each
outcome by including them inside the appropriate set of braces
Looping Statements
You'll occasionally want a group of statements to be executed repeatedly Two looping statements are supported by JavaScript The first, the for loop, is ideal for situations in which you want a group of instructions to occur a specific number of times The second, the while loop, is useful when you want a
Trang 5Basic JavaScript Programming
set of statements to be completed until a condition is satisfied
for Loops
The basic structure of a for loop looks like this:
for (var count = 1; count <= 10; ++count ) {
your statements go here
}
In this example, a variable called count is declared and set to a value of 1 Then a test is run to see whether the value of count is less than or equal to 10 If it is, all the statements inside the braces ({}) following the for statement are executed once The value of count is then incremented by 1 by the + +count statement, and the count <= 10 test is performed again If the result is still true, all the
instructions inside the braces are executed again This process proceeds until the value of count is
greater than 10, at which point the for loop ends In the preceding example, the variable count is
incremented using the increment operator, ++ The ++ appears before the variable name, which means that the variable is pre-incremented You could also write the expression as count++, which would post-increment the variable In this case, the results are the same, but if the expression were nested in a larger expression, like the one that follows, the results would differ Here's the example:
count++ <= 10
In that case, I post-increment the variable, so the variable of count before it is incremented would be compared to 10 Let's say I changed the expression to look like this:
++count <= 10
In that case, the value of count would be incremented before the comparison Check out the comments
in the example that follows to see what I'm talking about
count = 9;
return ++count <= 10; // returns true
count = 9;
return count++ <= 10; // returns false
Caution
As you can see, the for statement is self-contained The count variable is declared, tested,
and incremented within that statement You shouldn't modify the value of count within the
body of your loop unless you're absolutely sure of what you're doing If you modify count so that it never has a value greater than 10, your loop will never stop running and your
program won't work Anytime you use a for loop, you should avoid manipulating your
counter inside the loop; it's not a good programming practice
file:///G|/1/0672328860/ch12lev1sec4.html (3 von 5) [19.12.2006 13:49:31]
Trang 6while Loops
The basic structure of a while loop looks like this:
while ( condition ) {
your statements go here
}
Unlike the for loop, which has a built-in increment mechanism, the only test required for a while loop is
a true result from the condition test following the while statement This test could be an equivalence test, as in a == b, or any of the other tests mentioned previously with the if statement It might help you to think of a while loop as an if statement that's executed repeatedly until a condition is satisfied
As long as this expression is true, the statements inside the braces following the while loop continue to run foreveror at least until you close your web browser
If you prefer, you can write while loops with the condition at the end, which ensures that they always run once These are called do while loops, and look like this:
var color = "blue";
do {
// some stuff
}
while (color != "blue");
Even though the test in the loop will not pass, it will still run once because the condition is checked after the first time the body of the loop runs
Caution
When you're using while loops, you need to avoid creating infinite loops This means that
you must manipulate one of the values in the looping condition within the body of your
loop If you do manage to create an endless loop, about the only option you have is to shut
down the web browser If you're going to iterate a specific number of times using a
counter, it's usually best to just use a for loop
Trang 7Basic JavaScript Programming
Learning More About JavaScript
The list of statements, functions, and options included in this lesson represents only part of
the potential offered by JavaScript
For this reason, I cannot overemphasize the importance of the online documentation
provided by Netscape All the latest JavaScript enhancements and features will be
documented first at http://developer.mozilla.org/en/docs/JavaScript
file:///G|/1/0672328860/ch12lev1sec4.html (5 von 5) [19.12.2006 13:49:31]
Trang 8JavaScript enables HTML publishers to include simple programs or scripts within a web page without having to deal with the many difficulties associated with programming in high-level languages such as Java or C++
In this lesson, you learned about the <script> tag and how it's used to embed JavaScript programs into
an HTML document In addition, you explored the basic structure of the JavaScript language and some
of the statements and functions that it offers
With this basic knowledge behind you, in the next lesson, you'll explore some real-world examples of JavaScript and learn more about the concepts involved in JavaScript programming
Trang 9Workshop
The following workshop includes questions, a quiz, and exercises related to JavaScript
Q&A
Q Don't I need a development environment to work with JavaScript?
A Nope As with HTML, all you need is a text editor and a browser that supports
JavaScript You might be confusing JavaScript with Java, a more comprehensive programming language that needs at least a compiler for its programs to run
A The answer depends on what you mean by compatible Some of the syntax is similar
between Java and JavaScript, but the connection doesn't go much further than that
JavaScript scripts won't compile using a Java compiler, nor can Java programs be included in an HTML file the way JavaScript scripts can Java programs require a Java compiler and are then included as executable programs in web pages, whereas
JavaScript scripts are interpreted in code form as the HTML page is being downloaded
Q In Java and C++, I previously defined variables with statements such as int , char , and String Why can't I do this in JavaScript?
A As I mentioned previously, JavaScript is a loosely typed language This means that all variables can take any form and can even be changed on the fly As a result, the type
of value assigned to a variable automatically determines its type
Quiz
1. How is JavaScript different from Java?
2. How is JavaScript similar to Java (other than in name)?
3. What HTML tag did Netscape introduce to identify JavaScript scripts?
file:///G|/1/0672328860/ch12lev1sec6.html (1 von 3) [19.12.2006 13:49:32]
Trang 104. What are events? What can JavaScript do with them?
5. How are functions different from methods?
Quiz Answers
1. JavaScript is a simple language that works only in web browsers; Java is a more
comprehensive programming language that can be used just about anywhere
2. Because JavaScript scripts are run by the web browser itself, they're portable across any browser that includes JavaScript support, regardless of the computer type or operating system (like Java)
3. To accommodate the inclusion of JavaScript programs in a normal HTML document, Netscape introduced the <script> tag By placing a <script> tag in a document, you tell the web browser to treat any lines of text following the tag as script rather than as content for the web page
4. Events are special actions triggered by things happening in the system (windows opening, pages being loaded, forms being submitted) or by reader input (text being entered, links being followed, check boxes being selected) Using JavaScript, you can perform different operations in response to these events
5. Methods are associated with a specific object, and functions are standalone routines that operate outside the bounds of an object
Exercises
1. If you haven't done so already, take a few minutes to explore Netscape's online
documentation for JavaScript at http://devedge.netscape.com/central/javascript/ See whether you can find out what enhancements were included in JavaScript 1.5 that weren't included in earlier versions
2. Find a simple JavaScript script somewhere on the Webeither in use in a web page or in
an archive of scripts Look at the source code and see whether you can decode its logic and how it works