Basic 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.theSex.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. Figure lists the comparison operators currently recognized by JavaScript.

JavaScript Comparison Operators

Operator

Operator Description

Notes

==

Equal to

a == b tests to see whether a equals b.

!=

Not equal to

a != b tests to see whether a does not equal b.

<

Less than

a < b tests to see whether a is less than b.

<=

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.

>

Greater than

a > b tests to see whether a is greater than 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 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.


while 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.


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.




 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows