|
| |
Functions, Arrays, and Program Flow
Note: In syntax definitions, italics means that is something to be filled in,
"[]" mean that it is optional, and "..." mean that there can be more
than one.
Before you continue with this chapter, it might be beneficial to quickly look over the glossary.
In JavaScript, variable names (identifiers) start with a letter, and then can contain
up to 254 characters. Generally it is a good idea to stick to letters, numbers, and
underscores, but some other punctuation marks are allowed. Certain words cannot be
used for identifiers, as they are used by JavaScript. These are called reserved
words.
To set a value to a variable, you use the = operator. For example:
x = 8;
if (x == 8) alert("X is 8");
x = x + 9;
This example defines X as a variable, sets the value 8, shows a message if X is equal
to 8, and then adds 9 to the current value of X. Note that a variable can be used on
both sides of the = operator.
A function is easy to define. All you do is follow this syntax:
function identifier([parameter list]) {
*** JavaScript Code Here ***
}
Please note the the characters at the end of the first and third lines are not
parentheses. They are braces, usually made using [SHIFT]+[ and [SHIFT]+]. All
lines of code between the braces will be executed whenever the function is called.
The parameter list is optional. It is a list of identifiers, separated by commas.
If you wish the function to return a value
( If you wrote a function squared and had the line
x = squared(2) in your program, you would expect x to equal 4.
That's returning a value.), you should include a
return(value); statement in the function body (the "code
here" section). For example:
function squared(aNumber) {
return aNumber * aNumber;
}
(The asterisk is the JavaScript operator for multiplication.)
All variables in JavaScript are variants. They can hold one type of data in one
place in the script, and another later on. This code is valid:
X = 5;
X = "Hello";
X = 8.35;
X = true;
Many programming languages have variables which must be only one type, like integer,
string, decimal, etc., but JavaScript isn't like that. Thus, in some cases, it is
necessary to tell it to be a number rather than a string using eval(string).
Whenever you first start using a variable, the value is either a 0 (if it's a number)
or an empty string. This is called initialization.
Where you first use a variable (where it is initialized) is important. This
location determines where the variable can be used (the scope). If it is in a Script
tag, but not in a function, it is declared 'globally', meaning that you can use that
variable in any function on the page. If you put the Dim statement in a function, it
can only be used in that function.
<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">
<!--
X = 0;
function test1() {
Y = 30;
}
function test2() {
window.alert(X + Y);
}
test1();
test2();
//-->
</SCRIPT>
By now, you have already seen that you can write code directly in a Script tag, outside
of a function. Any statements in a Script tag but not in a function are run when the
browser reaches that point in the page. This allows you to add content to the middle
of a page easily.
The plus sign is used in JavaScript to attach two strings.
<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">
<!--
document.write("This page was updated " +
document.lastModified + ".<BR>");
//-->
</SCRIPT>
Below is what the above script would output.
Boolean values are either true or false. Internally, JavaScript always uses 1 for
true and 0 for false, though when it is converting numbers to boolean values, all non-zero
numbers are true. Other than converting number to boolean values, you can also get
boolean values by using comparison operators or logical operators.
| Comparison Operator |
Function |
Logical Operator |
Function |
| val1 == val2 |
True if they are the same (works on strings) |
val1 && val2 |
True if both are true |
| val1 != val2 |
True if they are not the same (works on strings) |
val1 || val2 |
True if one or both are true |
| val1 < val2 |
True if val1 is less than val2 |
!(val) |
True if val is false |
| val1 > val2 |
True if val1 is greater than val2 |
|
| val1 <= val2 |
True if val1 is either less than or the same as val2 |
| val1 >= val2 |
True if val1 is either greater than or the same as val2 |
| Arithmetic Operator |
Function |
| val1 + val2 |
Adds the values
(can also be used to
add the string val2 to
the end of string val1,
string concatenation) |
| val1 - val2 |
Subtracts val2 from val1 |
| val1 * val2 |
Multiplies the values |
| val1 / val2 |
Divides val1 by val2 |
| val1 % val2 |
Returns the remainder
of val1 being divided
by val2 |
Conditional statements allow you to make a section of code dependant on something else.
There is one basic form for a conditional statement in JavaScript, and it uses boolean
conditions.
if (condition) {
statement(s) if condition is true
} [else {
statement(s) if condition is false
}]
This can be used in situations where you only want to perform one action if the
condition is true, and possibly one if it is false. Ex:
if (userName == "George") {
alert("Hi, George.");
} else {
alert("You're not George.");
}
If there are many conditions, and depending on them, you want to take certain actions,
you can put one conditional statement inside another, nesting them. Ex:
aVar = Math.round(Math.random() * 2) + 1;
//Random number from 1 to 3
if (aVar == 1) {
alert("You got a one.");
} else {
if (aVar == 2) {
alert("You got a two.");
} else {
if (aVar == 3) {
alert("You got a
three.");
} else {
alert("You got a
wrong number.");
}
}
}
Looping structures are used to repeat a section of code, without having to write it
multiple times. Here, two looping structures will be covered. Together, these
two can be used to fill any need for looping. There are other looping structures
which are covered in the Netscape
JavaScript Reference.
- for (indexval = start; condition;
increment statement) {
statement(s)
}
- while (condition) {
statement(s)
}
The For loop is best used when you know how many times it should loop. The
Indexval is any variable. When the loop is entered, it becomes equal to Start.
Each time it reaches the end brace, it runs the increment statement, which is often
something simple like indexval = indexval + 1, but can be any statement
which changes the indexval. It continues to repeat the loop body until condition
is true.
The while loop is best used when you don't know how many times it should loop, such as
when reading in from a file which contains an unknown amount of data. The while loop
executes the statements as long as the condition is True. If the
condition is false when the program first arrives at the while loop, it will not execute
the statements at all. It is important to be careful when making loops, because if
the value of the condition doesn't change within the loop's statements, the loop will
never stop.
|