Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the...

61
Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have to compile it every time you change the code 3. List few things you can do with JS? Scrolling message on the status bar create banners, clocks, drop-down lists, mouse click functions etc…. 4. What are applets? Self-contained programmes that are written in Java and embedded within the web page
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    222
  • download

    1

Transcript of Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the...

Page 1: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Questions ?1. JavaScripts have to be compiled before they are executed. True/False2. What is the main advantage to interpreted languages? You don’t have to compile it every time you change the

code3. List few things you can do with JS? Scrolling message on the status bar create banners, clocks, drop-down lists, mouse click

functions etc….4. What are applets? Self-contained programmes that are written in Java and

embedded within the web page

Page 2: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

7. Explain the following JS code: 1: <script language=“JavaScript”> 2: function Greet (who) { 3: alert(“greetings,” + who); 4: } 5: </script> 6: script language=“JavaScript”> 7: Greet(“Fred”); 8: Greet(“Paul”); 9: </script>

Page 3: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

8. Where can you place the JS? Anywhere in the html document10. What are the most common languages used to create CGI programs? Perl, C, and Visual Basic11. What is the main disadvantage of CGI? The main disadvantage of CGI is that, since the data must be sent to

the Web server and back, response time may be slow!!12. What is ActiveX? ActiveX is a specification developed by Microsoft that allows ordinary

Windows programs to run within a Web page

Page 4: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

13. When a user views a page containing a JS program which machine actually executes the script

14. The date is a built in JS object True/False15. Explain the following line of JS code document.write(“ Welcome to my Web page”);16. Java programs are portable True/False17. How are java applets embedded on a Web page? <applet code=“Hello.class" width=“300" height="300">

Page 5: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

17. What are rollovers? MouseOver and MouseOut

18. What is a function? Functions are groups of JS statements that can be

treated as a single unit19. alert is a JS built in property True/false

20. Define the terms object, properties and method? Objects can store two or more pieces of data at once The items of data stored in an object are called the

properties of the objects Methods are functions that work with the object’s data

Page 6: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Using Variables Variables are named containers that can store data There are specific rules that must be followed when choosing

variable names: - Variable names can include letters of the alphabet, both upper-

and lowercase. They can also include the digits 0-9 and the underscore(_) character

- Variable names cannot include spaces or any other punctuation characters

- The first character of the variable name must be either a letter or an underscore

- Variable names are case sensitive- totalnum, Totalnum, TotalNum are separate variable names

- There is no limit on the length of variable names, but they must fit within one line

Page 7: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Examples of Variables Total_number_of_books LastStudentNumber task1 a _var32

Page 8: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Using local and global variables

JavaScript includes the var keyword which can be used to declare a variable

You can omit var in many cases and the variable is still declared the first time you assign a value to it

In order to understand the position where to declare a variable, you need to understand the concept of scope

A variable’s scope is the area of the script in which that variable can be used

There are two types of variables - Global variables - These have the entire script as

their scope - Local variables – These have a single function as their

scope

Page 9: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Global variables are declared in the main function outside any functions

e.g var students = 25; Any variable you declare in a function is a local

variablee.g The variables in the function’s parameter list are

local variables When creating local variables use the var keyword.

This forces the JS to create a local variable, even if there is a global variable with the same name

Page 10: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

1 <script LANGUAGE="JavaScript" type="text/javascript">2 var name1 = "Fred";3 var name2 = "Ethel";4 function Greet(who) {5 alert("Greetings," + who);6 var name2 = "Barney";7 }8 </script></head>9 <body>10 <h1>Function Example: the Sequel</h1>11 <p>Prepare to be greeted twice.</p>12 <script LANGUAGE="JavaScript" type="text/javascript">13 Greet(name1);14 Greet(name2);15 </script></body></html>

Page 11: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

name 1 and name2 are global variables defined in the header

who is a local variable created in the Greet() function’s parameter list

The tricky bit: The Greet() function creates a local variable called name2. Since var keyword is used, it does not affect the global variable name2

Note: It is a good practice to declare Global variables within the header of the HTML document as this will be executed first

If you attempt to use a variable before it is declared, it will contain the null value

Page 12: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

You can use any expression to the right of the equal sign, including other variables.

E.g. Lines = lines + 1; JavaScript includes two types of shorthand increment and

decrement variables - The first uses the += operator: e.g lines += 1; - similarly, you can subtract a number from a variable using the -=

operator: e.g lines -=1; JavaScript also includes the increment ++ and decrement --

operators e.g lines++; lines--;

Page 13: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

You can also use the ++ or -- operator before a variable name, as in ++ lines. However, these are not identical. The difference is when the increment or decrement happens:

- If the operator is after the variable name, the increment or decrement happens after the current expression is evaluated

- If the operator is before the variable name, the increment or decrement happens before the current expression is evaluated

Page 14: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Data Types in JavaScript In JS unlike other programming languages you don’t have to

specify a data type except in rare cases There are few basic data types JS uses: - Numbers, such as 3, 5, 21, or 1.3244. JS supports both integers

and floating-point numbers - Boolean, or logical values. These can have one of two values:

true or false. These are useful for indicating whether a certain condition is true

- Strings, such as “I am a jelly doughnut”. These consist of one or more characters of text

- The null value, represented by the keyword null. For example, the statement document.write(fig) will result in this value if the variable fig has not been previously used or defined

Page 15: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Converting Between Data Types JS handles conversion between data types e.g document.write(“The total is “ + total); This statement prints out a message such as “The total is

40”. Since the document.write function works with strings, the JS interpreter automatically converts any non-strings in the expression to strings before performing the function

In some situations, you may end up with a string containing a number and need to convert it to a regular numeric variable

JS includes two functions for this purpose: - parseInt() converts a string to an integer number - parseFloat() converts a string to a floating-point number

Page 16: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Stringvar = “30 angry polar bears” numvar = parseInt(stringvar); After these statements execute, the numvar

variable contains the number 30. The non-numeric portion of the string is ignored

These functions look for a number of the appropriate type at the beginning of the string. If a valid number is not found, the function returns the string “NaN”, meaning not a number

Page 17: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

One of the most common use of variables is to store information that comes from the user

To create a simple script that prompts the user for information and creates an HTML document

1. To begin the script, you will prompt for a first name, a last name, and a title for the page

These statements will prompt for three variables first = prompt(“Enter your first name.”); last = prompt(“Enter your last name.”); title = prompt(“Enter a page title”);

Page 18: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Use the contents of the variables to customize the HTML document

Begin with the title the user entered: document.write(“<H1>” + title + “</H1>”); The above statement adds the title to the page,

enclosed in <H1> tags. Then use the first and last names to give the user

credit: document.write(“<H2>By “+ first+ “ “ + last +

“</H2>”);

Page 19: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

1:<html><head><title>Customized home page</title></head>

2: <body>3: <script language=“JavaScript”>4: first = prompt(“Enter your first name.”);5: last = prompt (“Enter your last name.”);6: title = prompt(“Enter a page title.”);7: document.write(“<H1>” + title + “</H1>”);8: document.write(“<H2> By “ + first + “ “ + last + “</H2>”);9: </script>10: <p>This page is under construction11: </body></html>

Page 20: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Questions?? What is the importance of the var keyword? Should you

always use it to declare variables? Var keyword is only used to define a local variable in a

function, and then only if you want to ensure that a global variable of the same name is not used

Which of the following is not a valid JS variable name? a. 2names b. _first_and_last_names c. FirstAndLast

Page 21: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

If the statement var fig=2 appears in a function, which type of variable does it declare?

a. a global variable b. a local variable c. A constant variable What will be the result of the JS expression

31+ “ angry polar bears”? a. An error message b. 32 c. “31 angry polar bears”

Page 22: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Using String Objects

Strings store groups of text characters and are named similarly to other variables

e.g test= “This is a test”; JS stores strings as String objects. There are 2 ways

to create a new String object. 1. test = “This is a test”; 2. test = new String(“This is a test”); Note: The second statement uses the new keyword,

which is used to create new objects. This tells the browser to create a new String object containing the text This is a test and assigns it to the variable test

Page 23: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Assigning a Value

You can also assign a value after the string has already been created.

e.g test = “This is only a test.”;

You can also use the concatenation operator (+) to combine the values of two strings

Page 24: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

<html><head><title>String Test</title> </head> <body> <h1>String Test</h1> <script LANGUAGE="JavaScript">; test1 = "This is a test."; test2 = “So What!!"; both = test1 + test2; alert(both); </script> </body> </html>

Page 25: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

In addition to using the + operator to concatenate two strings, the += operator can be used to add to a string

E.g sentence +=“.”;

Page 26: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Calculating the String’s Length Sometimes you may find it useful to know the length of

the string variable. You do this with the length property of the String objects To use this property, type the string’s name followed

by .lengthe.g test.length refers to the length of the test string test = “This is a test.”; document.write(test.length);The first statement assigns the string to the test variableThe second statement displays the length of the string – in

this case 15 characters.

Page 27: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Converting the String’s Case Two methods of the String object allow you to convert the

contents of a string to all uppercase or all lowercase: - toUpperCase() converts all characters in the string to

uppercase - toLowerCase() converts all characters in the string to

lowercasee.g document.write(test.toLowerCase()); The above statement will display the value of the test

string variable in lowercase Note: This will not change the string. To change the string

value test = test.toLowerCase();

Page 28: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Working with Substrings

JS allows you to work with substrings, or portions of a string.

You can use the substring method to retrieve a portion of a string, or the charAt method to get a single character

The substring() method returns a string consisting of a portion of the original string between two index values, which you must specify in parenthesis

E.g document.write(alpha.substring(0,4)); alpha= “ABCDEFGHIJKLMN” alpha.substring=ABCD

Page 29: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Getting a Single character

The charAT method is a simple way to grab a single character from a string. You specify the character’s index, or position, in parentheses

e.g alpha=“ABCDEFGHIJKLMNOP” alpha.charAT(0) returns A alpha.charAT(12) returns M alpha.CharAT(27) returns an empty string

because there is no character at that position

Page 30: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Using Numeric Arrays An array is a numbered group of data items you can

treat as a single unit E.g you can use an array called scores to store several

scores for a game Arrays can contain strings, numbers, objects, or other

types of data Unlike other JS variables you have to declare an array

before using it.e.g scores = new Array(30); To assign values to an array, use brackets and index.

Indices begin with 0, so the elements of the array in this example would be numbered 0 to 29.

e.g scores[0] = 39; etc

Page 31: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Like strings, arrays have a length property. This tells you the number of elements in the array, usually the same number you used when creating the array

e.g document.write(scores.length);

To read the contents of the array you can use the same notation as that used to assign values.

e.g scoredisp = “Scores: “+ scores[0] +”,” + scores[1]+ “,” + scores[2] + “,” + scores[3];

document.write(scoredisp);

Page 32: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Splitting a String JS includes a string method called split, which splits a string into

its component parts. To use this method, specify the string to split and a character to divide the parts:

test = “John Q. Public”; parts = test.split(“ “); The split method in the second statement splits the name string

at each space, resulting in three strings. These are stored in a string array called parts. After the

execution of the statement parts will contain parts[0] = “John” parts[1] = “Q.” parts[2] = “public”

Page 33: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

JS also includes an array method, join, that performs the opposite function.

fullname = parts.join(“ “); The value in the parentheses specifies a character to

separate the parts of the array In the example here the final string will be “John Q.

Public.”

Page 34: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Sorting an Array

JS also includes a sort method for arrays, which returns a sorted version of the array (alphabetically or numerically)

e.g: names[0] = “Public, John Q.”; names[1] = “Tillman, Henry J.”; names[2] = “Clinton, Bill”; names[3] = “Mouse, Mickey”; sortednames = names.sort();The last statement assigns the sortednames array to

the sorted version of names using the join method

Page 35: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Scrolling message Program Now use the variables, strings and the operators we have

learned to write the scrolling message programStep1: To begin you’ll need to define the message to be

scrolled. msg = “ Welcome to my page”;Step2: Define a second string called spacer. This string will

be displayed between the copies of the message to make it clear where one ends and the other begins.

spacer = “ … …”;Step3: A numeric variable to store the current position of

the string. Call it pos and initialise it with 0; pos=0;

Page 36: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

1: function ScrollMessage() {2: window.status = msg.substring(pos, msg.length) + spacer + msg.substring(0,pos);3: pos++;4: if (pos > msg.length) pos = 0;5: window.setTimeout (“ScrollMessage()”, 200);6: }Line1: The function keyword is used to begin the functionLine2: This statement displays a string in the status line. This string is composed of the portion of msg from pos to end, followed by the space, followed by the portion of msg from the beginning to posLine3: The pos variable is incrementedLine4: This statement checks whether pos is larger than the length of msg. If it is, it resets it to

0.Line5: This statement uses the Window.setTimeout method, which allows you to set a statement to be executed after a time delay.

 

Page 37: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

3: <script LANGUAGE="JavaScript"> 4: msg = "This is an example of a scrolling message.

Isn't it exciting?"; 5: spacer = "... ..."; 6: pos = 0; 7: function ScrollMessage() { 8: window.status = msg.substring(pos, msg.length)

+ spacer + msg.substring(0, pos); 9: pos++; 10: if (pos > msg.length) pos = 0; 11: window.setTimeout("ScrollMessage()",200); 12: } 13: ScrollMessage(); 14: </script> 15: </head>

Page 38: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

The if Statement

The if statement is the main conditional statement in JS.

In plain English If the phone rings, answer it. This statement consists of two parts: a condition (If

the phone rings) and an action (answer it)

If (a==1) window.alert(“Found a 1!); This statement includes a condition (if a equals 1)

and an action (display a message). You can also use multiple statements for action

Page 39: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

1: if (a==1) {2: window.alert(“Found a 1!);3: a = 0;4: } The above block of statements checks

the variable a once again If it finds a value of 1, it displays a

message and sets a back to 0

Page 40: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Conditional Operators Between two values to be compared is a conditional

operator The list of conditional operators available are: 1. == (is equal to) 2. != (is not equal to) 3. < (is less than) 4. > (is greater than) 5. <= (is less than or equal to) 6. >= (is greater than or equal to)

Page 41: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Combining Conditions with Logical Operators

JS includes logical operators, also known as Boolean operators

e.g if (phone == “ “) window.alert (error!”); if (email == “ “) window.alert (“error!”); Using a logical operator, you can combine them into a

single statement: if (phone == “ “ ¦¦ email == “ “)

window.alert(“error!”); The above statement uses the logical Or operator (¦¦)

to combine the conditions In English this would be “If the phone number or the

email address is blank, display an error message.

Page 42: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

An additional logical operator is the And operator, (&&). if (phone == “ “ && email == “ “) window.alert(“error!”; Using the above statement the error message will be

displayed if both the email address and phone number variables are blank

The third logical operator is the exclamation mark (!), which means Not.

Not operator is used to invert an expression. A true expression become false and a false one would become true.

e.g if (phone != “ “) alert (“phone is OK”);

Page 43: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

The else Keyword Much like its English equivalent, else tells the JS

interpreter what to do if the condition isn’t true1: if (a==1) {2: alert(“Found a 1!);3: a = 0;4: }5: else {6: alert(“Incorrect value: “ +a);7: } This displays a message and resets the variable a if the

condition is met. If the condition is not met (if a is not 1), a different message is displayed.

Page 44: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Using Conditional Expressions In addition to the if statement, JS provides a

shorthand type of conditional expression that you can use to make quick decisions

A conditional expression looks like this: variable = (condition) ? If true : if false This assigns one of the two values to the

variable: one if the condition is true, and another if it is false

Page 45: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

e.g value = (a==1) ? 1 : 0;The above statement is equivalent to if (a==1) value = 1; else value = 0; The value after the question mark (?) will be used if the

condition is true, and the value after the colon (:) will be used if the condition is false. The colon represents the else portion

e.g document.write(Found” + counter + ((counter == 1) ? Word.” : “ words.”));

Page 46: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Using Multiple Conditions with switch

1: if (button==“next”) window.location=“next.html”;2: if (button==“previous”) window.location=prev.html”;3: if (button==“home”) window.location=“home.html”);4: if (button==“back”) window.location=“menu.html”);

Although this is very compact code this method can get messy if each if statement has its own block of code with several statements

Page 47: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Switch statement

1: switch (button) {2: case “next” :3: window.location=“next.html;4: break;5: case “previous” :6: window.location=“prev.html”; break;7: default : window.alert (“Wrong button.”);8: }

Page 48: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Switch statement

The initial switch statement includes the value to test (in the example button) in parentheses

Braces ({ and }) encloses the switch statement, similar to a function or an if statement

One or more case statements. Each of these statements specifies a value to compare with the value specified in the switch statement. If it matches the statement after the case is executed. Otherwise the next case is tried

The break statement is used to end each case The default statement can be included and followed by

a default case- one or more statements that are executed if none of the case statement were matched

Page 49: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Evaluating a User Response This script asks the user a question and then evaluates

the user’s response to determine what to do next. The script starts by prompting the user with the

window.prompt function Here is the prompt statement: where= window.prompt(“Where do you want to go

today?”);Next use the switch statements switch (where) { case “Netscape” : window.location=http://www.netscape.com;

break;

Page 50: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

case “Microsoft” : window.location=“http://www.microsoft

.com”; break; case “Yahoo” : window.location=“http://www.yahoo.com”; default : window.location=“http://www.city.ac.uk”;}

Page 51: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

<body> <H1>User Response Example</</H1> Enter your destination. <BR> <script language=!JavaScript1.2”> where = window.prompt(“Where do you want to go

today?”); switch (where) { case “Netscape” : window.location=“http://www.netscape.com”; break; case “Microsoft” : window.location=“http://www.microsoft.com”; break; </script> </body> </html>

Page 52: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Using for Loops The for keyword is the first tool to consider for creating

loops A for loop uses a variable (called a counter or index) to

keep track of how many times the loop has executed, and it stops when the counter reaches a certain number

A basic for statement looks like: for (var = 1; var < 10; var++) { - The first parameter (var=1) specifies a variable and

assigns an initial value to it called the initial expression - The second parameter (var < 10) is a condition that must

remain true to keep the loop called the increment expression

- The third parameter (var++) is called the increment expression

Page 53: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

1: for (i=1; i<10; i++) {2: document.write(“This is line “, I, “\n”);3: } Output This is line 1 This is line 2 This is line 3 -- -- This is line 9 The loop will only be executed 9 times because i<10

is the condition

Page 54: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Using while Loops Unlike the for loops, while loops don’t necessarily use

a variable to count. Instead they execute as along as (while) a condition is true

If the condition starts out as false, the statements might not execute at all

1: while (total < 10) {2: n++;3: total += values[n];4: } This loop uses a counter, n, to iterate through the

values array

Page 55: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Using do..while Loops This type of loop is similar to the while loop, with

one difference: The condition is tested at the end of the loop rather than at the beginning

1: do {2: n++;3: total += values[n];4: }5: while (total < 10); Note: The statements in the loop will always be

executed at least once, even if the condition is never true

Page 56: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Creating an Infinite Loop

1: while (j < 10) {2: n++;3: values[n] = 0;4: } There is a mistake in this example. The variable j

doesn’t actually change during the loop. This will create an infinite loop. The loop will

continue executing until it is stopped by the user, or until it generates an error of some kind

JS won’t give you an error that actually tells you there is an infinite loop.

Page 57: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Escaping from a Loop There is one way out of an infinite loop. You can use the break

statement during a loop to exit it immediately and continue with the first statement after the loop

1: while (true) {2: n++;3: if (values[n] == 1) break;4: } Although the while statement is set up as an infinite loop, the

if statement checks the corresponding value of an array. If it finds a 1, it exits the loop

Note: While the JS interpreter encounters a break statement, it skips the rest of the loop and continues the script with the first statement after the right brace at the loop’s end

Page 58: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Continuing a Loop The continue statement skips the rest of the loop, but

unlike break, it continues with the next iteration of the loop1: for (i=1; i<21; i++) {2: if (score[i]==0) continue3: document.write(“Student number “, i, “Score: “, score[i], “\

n”);4: } This script prints the scores for 20 students, stored in the

score array The if statement is used to check for scores with a value of

0. The script assumes that a score of 0 means that the student didn’t take the test, so it continues the loop without printing that score

Page 59: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

Using for..in Loops This is designed to perform an operation on each

property of an object E.g the navigator object contains properties that describe

the user’s browser, you can use it to display this object’s properties:

for (i in navigator) { document.write (“property: “ + i); document.write(“value: “ navigator[i]); } For each iteration of the loop, the variable is set to the

next property of the object. This makes it easy when you need to modify each of an object’s properties

Page 60: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

<script language=“JavaScript1.3”> names = new Array(); i = 0; do { next = window.prompt(“Enter the Next Name”); if (next > “ “ && next != “undefined”) names[I] = next; i = i+1; } while (next > “ “ && next !=“undefined”); document.write (“<H2>” + (names.length) + “names.entered”. “</H2>”); document.write(“<OL>”); for (I in names) { document.write(“<LI>” + names[I] + “<BR>”); }Document.write(“/OL>”);</script>

Page 61: Questions ? 1. JavaScripts have to be compiled before they are executed. True/False 2. What is the main advantage to interpreted languages? You don’t have.

document.write(“<OL>”); for (I in names) { document.write(“<LI>” + names[I] + “<BR>”); } document.write(“/OL>”); This part of the script will display all the names entered in the order do { next = window.prompt(“Enter the Next Name”); if (next > “ “ && next != “undefined”) names[I] = next; i = i+1; } This loop prompts for a string called next. If a name was entered it will be

stored in the next entry in the names array The loop repeats until the user doesn’t enter a name or clicks Cancel in the

Prompt dialog