04 Javascript
04 Javascript
Outline
Introduction Fundamental of Javascript:
Keywords, variables, operators Control Statements Functions Arrays Objects
Reference: Internet & World Wide Web: How To Program, 3rd Ed., Dietel & Goldberg, Prentice Hall
Introduction to Javascript
To make web pages more dynamic and interactive An Interpreter-based language It isnt Java Case-sensitive Must be embedded into HTML Browser dependent
Introduction to Javascript
Embedding Javascript into HTML: <script type=text/javascript> <! Javascript code goes here // -> </script>
<script language=javascript>
<!
</script>
Internal script:
Simple Program
<html> <head> <title>A First Program in JavaScript</title> <script type = "text/javascript"> <!-document.writeln( "<h1>Welcome to JavaScript Programming!</h1>" ); // --> </script> </head> <body></body> </html>
Output:
Debugging Errors:
Click this.
Warning icon means there are some errors in your script
Debugging Errors:
External script:
Simple Program
<html> <head> <title>A First Program in JavaScript</title> <script type = "text/javascript src = welcome.js> </script> </head> <body></body> </html>
Output:
Simple Programs
Example 2: displaying simple message box using alert dialog
<html> an alert dialog to the user. <head> <title>Printing Multiple Lines in a Dialog Box</title> <script type = "text/javascript"> <!-window.alert( "Welcome to\nJavaScript\nProgramming!" ); // --> When the alert dialog displays, the string </script> passed as its one argument is displayed. </head> <body> character that places all remaining text on the <p>Click Refresh (or Reload) to run this script again.</p> next line. </body> </html>
Simple Programs
Output:
Esc a p e seq ue nc e
De sc rip tio n
\n \t \r
Newline. Position the screen cursor at the beginning of the next line. Horizontal tab. Move the screen cursor to the next tab stop. Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. Backslash. Used to represent a backslash character in a string. Double quote. Used to represent a double quote character in a string contained in double quotes. For example, window.alert( "\"in quotes\"" ); displays "in quotes" in an alert dialog.
\\ \"
\'
Single quote. Used to represent a single quote character in a string. For example, window.alert( '\'in quotes\'' ); displays 'in quotes' in an alert dialog.
Fig. 7.5
Simple Programs
Example 3: getting user input using prompt dialog
<html> <head> <title>Using Prompt Box</title> This <script type = "text/javascript"> <!-var name; // string entered by the user
// read the name from the prompt box as a string name = window.prompt ("Please enter your name", "Ali"); document.writeln("<h1>Hello, " + name + ", welcome to JavaScript Programming!</h1>" ); // --> </script> The window method prompt displays </head>
<body> <p>Click Refresh (or Reload) to run this script again.</p> </body> </html>
Simple Program
Output:
Keywords
Ja va Sc rip t Ke yw ord s
break
case
continue
do if switch void
else false for in new null this true typeof while with Keywords that are reserved, but not used by JavaScript catch class const enum export extends super try Fig. 8.2 Ja va Sc rip t ke yw ord s.
debugger finally
default import
Arithmetic operators:
Ja va S c rip t op era tio n Arithm etic op era tor
Operators
Alg eb ra ic exp ression Ja va S c rip t exp ression
+ * / %
op e ra tors.
f + 7 p - c b * m x / y r % s
Relational operators:
S ta nd a rd a lg eb ra ic eq ua lity op era tor or rela tiona l op era tor Ja va S c rip t eq ua lity or rela tio na l op era tor S a m p le Ja va S c rip t c o nd itio n Mea ning of Ja va S c rip t c o nd itio n
Equality operators
=
Relational operators
> <
x is equal to y x is not equal to y x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y
Operators
Typ e
left to right left to right left to right left to right left to right right to left
Variables
Declaring and assigning variables:
var variable1; var variable2 = 100; variable3 = 3.823; // example 1 declaring a variable without any value // example 2 declaring and assigning a variable // example 3 assigning without declaring first
Selections
if statement
Three forms of if statements are shown at the next table.
if(condition) statement; if (condition) { statement; statement; } if (condition) { statement; statement; } else { statement; statement; }
Examples:
if statement
if (score > 50)
document.write(FAIL);
else
document.write(FAIL);
if (score > 90) document.write(Grade A); else if (score > 75) document.write(Grade B); else if (score > 60) document.write(Grade C); else if (score > 50) document.write(Grade D); else document.write(Grade F);
switch statement
switch (expression) { case value1: statements_1; break; case value2 : statements_2; break; ... default : statements; break; } 3. How the switch statement works?
1.
2.
switch statement
Example: var value = 2;
it is not equal to this case-value (i.e. 2!=1). So, skip the statements of case 1 and move to the next case. it is equal to this case-value (i.e. 2==2). So, execute the statements of the case 2. this expression evaluates to 2
break; }
Output:
Two
Repetitions
for loops
for (initialization; condition; update) { statements; }
Example: Prints odd numbers between 0 10.
while loops
while (condition) { statements; }
Example: Prints odd numbers between 0 10.
var n=1;
while (n<10) { document.write(n + <br>); n +=2; }
Output: 1 3 5 7 9
do-while loops
do { statements; } while (condition)
Example: Prints odd numbers from 1 9.
var n=1;
do { document.write(n + <br>); n +=2; } while (n<10)
Output: 1 3 5 7 9
Jump Statements
Jump statements
Repetition of a loop is controlled by the loop condition. We can alter the flow of control by using using jump statements. Javascript provides three jump statements:
break statement
It causes a loop to terminate Example: for (n=10; n>0; n=n-1) { if (n<8) break; document.write(n, ); } Output: 10 9 8
break statement
Output: 5 5 4 4
continue statement
In while and dowhile loops, the continue statement transfers the flow of control to the loop condition. In for loop, the continue statement transfers the flow of control to the updating part.
continue statement
Example:
Output: 10 8 6 4 2
Output: 0 2 4 0 2 0
return statement
It causes a function to terminate.
Example:
function print_numbers() { var n=10; var i; while (n>0) { for (i=n;i>0; i--) { if (i%2==1) continue; if (i%4==0) break; if (n==6) return; document.write(i, ); } document.writeln(<br>"); n=n-1; } The return statement terminates the function and returns to the caller.
Output: 10
The continue statement transfers control to the updating part ( i-- ) The break statement terminates the for loop.
return statement
When to use return? Example: the following functions are equivalent
function calc_point(grade) { var result; if (grade=='A') result = 4.0; else if (grade=='B') result = 3.0; else if (grade=='C') result = 2.5; else if (grade=='D') result = 2.0; else result = 0.0; return result; } function calc_point(grade) { if (grade=='A') return 4.0; if (grade=='B') return 3.0; if (grade=='C') return 2.5; if (grade=='D') return 2.0; return 0.0; }
The else part of each if statement may be omitted. It has never been reached.
return statement
function calc_point3(grade) { var result; switch (grade) { case 'A': result = 4.0; break; case 'B': result = 3.0; break; case 'C': result = 2.5; break; case 'D': result = 2.0; break; default: } return result; } result =0.0;
function calc_point4(grade) { switch (grade) { case 'A': return 4.0; case 'B': return 3.0; case 'C': return 2.5; case 'D': return 2.0; } return 0.0; }
The break statement of each case may be omitted. It has never been reached.
Functions
Creating functions
Involves two steps: Define: to define what processes should be taken Call/Invoke: to execute the functions Syntax of function definition: function function_name (param1, param2, .., param_n)
//parameters are optional
{
//functions code goes here
function hello() { alert(Hello World); } </script> </head> <body onLoad=javascript:hello();> <!- function invocation--> </body> </html>
Arrays
Creating arrays
var a = new Array(12);// var b = new Array(); //
create 12-element array create an empty array
// same as array c
2.34 Ali 20 10
(cont.)
10 20
Ali
2.34
Objects
Creating classes
function class_name { this.property_1 . . . this.property_n this.method_1 = . . . this.method_n = } (property_1, . . ., property_n) = property_1 = property_n method_name_1 method_name_n
Creating classes
Example:
function Person(aName,age) { this.name = aName; this.age = age; this.displayInfo = print; } function print() { window.alert(Name= + this.name + \nAge= + this.age); }
(cont.)
Example:
// creating an object of class Person
person1 = new Person(Ali,20); // displaying info of person1 person1.displayInfo(); // changing property person1.age=23;
Example:
Array of objects
var person_list = new Array(); // creating array // inserting objects into the array elements person_list[0]= new Person(Ali,20); person_list[1]= new Person(Aminah,24); person_list[2]= new Person(Bakar,19); // displaying info of all persons
Reference
Sebesta, R. W., Programming the World Wide Web, (2009), 5th Edition, Pearson. Deitel P. J, Deitel H. M., Internet & World Wide Web: How To Program, (2007), 5th Edition, Prentice Hall. Anderson-Freed S., (2001), Weaving A Website: Programming in HTML, JavaScript, PHP and Java. Prentice Hall