|
|
JavaScript Tutorial
To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following: 5. ArraysAn Array is an object which stores multiple values and has various properties. When you declare an array, you must declare the name of it, and then how many values it will need to store. It is important to realize that each value is stored in one of the elements of the array, and these elements start at 0. This means that the first value in the array is really in the 0 element, and the second number is really in the first element. So for example, if I want to store 10 values in my array, the storage elements would range from 0-9. The notation for declaring an array looks like this:
Initially, all values are set to null. The notation for assigning values to each unit within the array looks like this:
By putting the element number in brackets [ ] after the array's name, you can assign a value to that specific element. Note
that there is no such element, in this example, as In JavaScript, however, an array's length increases if you assign a value to an element higher than the current length of the array. The following code creates an array of length zero, then assigns a value to element 99. This changes the length of the array to 100.
Be careful to reference the right cells, and make sure to reference them properly!
Because arrays are objects, they have certain properties that are pre-defined for your convenience. For example,
you can find out how many elements
6. OperatorsJavaScript has many different operators, which come in several flavors, including binary. This tutorial will cover some of the most essential assignment, comparison, arithmetic and logical operators. 6.1. Selected assignment operatorsAn assignment operator assigns a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. The other operators are shorthand for standard operations. Find an abridged list of shorthand operators below:
Note that the = sign here refers to assignment, not "equals" in the mathematical sense. So if x is 5 and y is 7,
EXAMPLES: If x = 10 and y = 2, x += y would mean x = x + y, hence x's new value would be the sum of x's previous value plus y's previous value. Upon executing x = x + y = 10 + 2, x's new value becomes 12, while y's new value remains equal to its old value. Similarly, x -= y would change x's value to 8. Calculate x *= y and x /= y to get a better idea of how these operators work. 6.2. Comparison operatorsA comparison operator compares its operands and returns a logical value based on whether the comparison is true or not. The operands can be numerical or string values. When used on string values, the comparisons are based on the standard lexicographical ordering. They are described in the following table.
EXAMPLES: 5 == 5 would return TRUE. 5 != 5 would return FALSE. (The statement 'Five is not equal to five.' is patently false.) 5 <= 5 would return TRUE. (Five is less than or equal to five. More precisely, it's exactly equal to five, but JavaScript could care less about boring details like that.) 6.3. Selected Arithmetic OperatorsArithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), division (/) and remainder (%). These operators work as they do in other programming languages, as well as in standard algebra. Since programmers frequently need to add or subtract 1 from a variable, JavaScript has shortcuts for doing this. myVar++ adds one to the value of myVar, while myVar-- subtracts one from myVar. EXAMPLES: Let x = 3.
6.4. Logical OperatorsLogical operators take Boolean (logical) values as operands and return a Boolean value. That is, they evaluate whether each subexpression within a Boolean expression is true or false, and then execute the operation on the respective truth values. Consider the following table:
EXAMPLES: Since we have now learned to use the essential operators, we can use them in conjunction with one another. See if you can work out why the following examples resolve the way they do: If x = 4 and y = 7, ((x + y + 2) == 13) && (((x + y) / 2) == 2) returns FALSE. If x = 4 and y = 7, ((y - x + 9) == 12) || ((x * y) == 2) returns TRUE. If x = 4 and y = 7, !((x/2 + y) == 9) || ((x * (y/2)) == 2) returns FALSE. 7. Using JavaScript ObjectsWhen you load a document in your web browser, it creates a number of JavaScript objects with properties and capabilities based on the HTML in the document and other pertinent information. These objects exist in a hierarchy that reflects the structure of the HTML page itself. The pre-defined objects that are most commonly used are the
...pops up an alert box displaying the given message. Try it yourself by clicking on this link. The The objects in this pre-defined hierarchy can be accessed and modified.
To refer to specific properties, you must specify the property name and all its
ancestors, spelling out the complete hierarchy until the
document.myform.text1.value
Form elements can also be accessed through the aforementioned
document.forms[0].elements[2].value Functions (capabiltiies) of an object can similarly be accessed using the period notation. For example, the following instruction resets the 2nd form in the document. document.forms[2].reset(); Click on one of the objects below to view the Netscape documentation on the specific properties and methods that that object has:
8. FunctionsFunctions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure -- a set of statements that performs a specific task. A function definition has these basic parts:
8.1. Defining a FunctionWhen defining a function, it is very important that you pay close attention to the syntax. Unlike HTML, JavaScript is case sensitive, and it is very important to remember to enclose a function within curly braces { }, separate parameters with commas, and use a semi-colon at the end of your line of code. It's important to understand the difference between defining and calling a function. Defining the function names the function and specifies what to do when the function is called. You define a function within the <SCRIPT>...</SCRIPT> tags within the <HEAD>...</HEAD> tags. In defining a function, you must also declare the variables which you will be calling in that function. Here's an example of defining a function: function popupalert() { alert('This is an alert box.'); } Notice the parentheses after the function name. It is imperative that you include these parentheses, even if they are empty. If you want to pass a parameter into the function, you would include that parameter inside of the parentheses. A parameter is a bit of extra information that cn be different each time the function is run. It is stored in a variable and can be accessed just like any other variable. Here's an example of a function that takes a parameter: function anotherAlert(word) { alert(word + ' is the word that you clicked on'); } When you call this function, you need to pass a parameter (such as the word that the user clicked on) into the function. Then the function can use this information. You can pass in a different word as a parameter each time you call the function, and the alert box will change appropriately. You'll see how to pass a parameter a little later on. You can pass in multiple parameters, by separating them with a comma. You would want to pass in a few parameters if you have more than one variable that you either want to change or use in your function. Here are two examples of passing in multiple parameters when you are defining the function:
function secondAlert(word,password) { confirm(word + ' is the word that you clicked on. The secret password is ' + password); } function thirdAlert(word,password) { confirm(word + ' is the word you clicked on. Please take note of the password, ' + password); } You'll notice that the same parameters are passed into both of these functions. However, you can pass in whatever values you want to use (see this same example below in calling the function). 8.2. Calling a FunctionCalling the function actually performs the specified actions. When you call a function, this is usually within the BODY of the HTML page, and you usually pass a parameter into the function. A parameter is a variable from outside of the defined function on which the function will act.
Here's an example of calling the same function:
For the other example, this is how you may call it:
<A HREF="#top" onClick="anotherAlert('top')">top</A> This would bring you to the top of the page, and bring up an alert box that said: "top is the word you clicked on" Try it for yourself: top Here is the same example with multiple parameters that was shown above:
<A HREF="#top" onClick="secondAlert('awesome','pandas')">awesome</A> <A HREF="#top" onClick="thirdAlert('computers','insert')">computers</A>
You'll notice in the code that different values for the variables
Try it for yourself: When you click on the words below, a confirmation box will pop up and then the link will bring you to the top of the page. 9. If/Else Statementsif statements execute a set of commands if a specified condition is true. If the condition is false, another set of statements can be executed through the use of the else keyword.
The main idea behind if statements is embodied by the sentence: "If the weather's good tomorrow, we'll go out and have a picnic and Lisa will do cartwheels -- else, we'll stay in and Catherine will watch TV." As you can see, the idea is quite intuitive and, surprisingly enough, so is the syntax: if (condition) { statements1 } -or- if (condition) { statements1 } else { statements2 } (An if statement does not require an else statement following it, but an else statement must be preceded by an if statement.) condition can be any JavaScript expression that evaluates to true or false. Parentheses are required around the condition. If condition evaluates to true, the statements in statements1 are executed. statements1 and statements2 can be any JavaScript statements, including further nested if statements. Multiple statements must be enclosed in braces.
Here's an example: if (weather == 'good') { go_out(we); have_a_picnic(we); do_cartwheels(Lisa); } else { stay_in(we); watch_TV(Catherine); } 10. LoopsLoops are an incredibly useful programming tool. Loops handle repetitive tasks extremely well, especially in the context of consecutive elements. Arrays immediately spring too mind here, since array elements are numbered consecutively. It would be quite intuitive (and equally practical), for instance, to write a loop that added 1 to each element within an array. Don't worry if this doesn't make a lot of sense now, it will, after you finish reading the tutorial.
The two most common types of loops are for and while loops: 10.1. for LoopsA for loop constitutes a statement which consists of three expressions, enclosed in parentheses and separated by semicolons, followed by a block of statements executed in the loop. This definition may, at first, sound confusing. Indeed, it is hard to understand for loops without seeing them in action. A for loop resembles the following: for (initial-expression; condition; increment-expression) { statements } The initial-expression is a statement or variable declaration. (See the section on variables for more information.) It is typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword.
The condition is evaluated on each pass through the loop. If this condition
evaluates to true, the statements in statements are performed. When the condition
evaluates to false, the execution of the
The increment-expression is generally used to update or increment the counter variable.
The statements constitute a block of statements that are executed as long as condition evaluates to true. This can be a single statement or multiple statements. Although not required, it is good practice to indent these statements from the beginning of the for statement to make your code more readable.
Check out the following for statement. It starts by declaring the variable i and initializing it to zero. It checks whether i is less than nine, performs the two successive statements, and increments i by one after each pass through the loop:
var n = 0; for (var i = 0; i < 3; i++) { n += i; alert("The value of n is now " + n); } Try it yourself: Click this link 10.2. while LoopsThe while loop, although most people would not recognize it as such, is for's twin. The two can fill in for one another - using either one is only a matter of convenience or preference according to context. while creates a loop that evaluates an expression, and if it is true, executes a block of statements. The loop then repeats, as long as the specified condition is true. The syntax of while differs slightly from that of for: while (condition) { statements } condition is evaluated before each pass through the loop. If this condition evaluates to true, the statements in the succeeding block are performed. When condition evaluates to false, execution continues with the statement following statements. statements is a block of statements that are executed as long as the condition evaluates to true. Although not required, it is good practice to indent these statements from the beginning of the statement. The following while loop iterates as long as n is less than three.
var n = 0; var x = 0; while(n < 3) { n++; x += n; alert("The value of n is " + n + ". The value of x is " + x); } Try it for yourself: Click this link 11. CommentingComments allow you to write notes to yourself within your program. These are important because they allow someone to browse your code and understand what the various functions do or what your variables represent. Comments also allow you to understand your code if it's been a while since you last looked at it. In JavaScript, you can write both one-line comments and multiple line comments. The notation for each is different though. For a one line comment, you precede your comment with //. This indicates that everything written on that line, after the //, is a comment and the program should disregard it. For a multiple-line comment, you start with /* and end with */ . It is nice to put an * at the beginning of each line just so someone perusing your code realizes that he/she is looking at a comment (if it is really long this helps). This is not necessary though. The following are examples of comments in JavaScript.
// This is a single line comment. /* This is a multiple line comment with only one line. */ /* This is a multiple line comment. * The star (*) at the beginning of this line is optional. * So is the star at the beginning of this line. */
For more detailed explanations or further help, see
Netscape's JavaScript Reference Guide for
JavaScript 1.1. Make sure that if you consult other sources that they are refering to JavaScript 1.1. This is the version that is compatible with
Netscape 3.0, so if you use code that is not recognized by JavaScript 1.1, it will not work when your paged is browsed in Netscape 3.0.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||