Chapter 8 - JavaScript/JScript: Introduction to Scripting

Chapter 8 - JavaScript/JScript:
Introduction to Scripting
Outline
8.1
8.2
8.3
8.4
8.5
8.6
8.7
Introduction
A Simple Program: Printing a Line of Text in a
Web Page
Another JavaScript Program: Adding Integers
Memory Concepts
Arithmetic
Decision Making: Equality and
Relational Operators
JavaScript Internet and World Wide Web
Resources
 2000 Deitel & Associates, Inc. All rights reserved.
8.1 Introduction
• JavaScript scripting language
– Originally created by Netscape
– Facilitates disciplined approach to designing computer
programs
– Enhances functionality and appearance of Web pages
• Jscript
– Microsoft’s version of JavaScript
 2000 Deitel & Associates, Inc. All rights reserved.
8.2 A Simple Program: Printing a Line of Text in a
Web Page
• Browser includes JavaScript Interpreter
– Processes JavaScript commands
• Whitespace
– Blank lines, space characters, tab characters
– Generally ignored by browser
– Used for readability and clarity
• <SCRIPT>…</SCRIPT> tag:
– Encloses entire script
– Attribute LANGUAGE=“JavaScript”
• Indicates scripting language (JavaScript default in IE5 & Netscape)
– Tag must be closed at the end of the script
 2000 Deitel & Associates, Inc. All rights reserved.
8.2 A Simple Program: Printing a Line of Text in a
Web Page (II)
• Correct method call syntax:
– object.method( “string”, “[additional arguments]” );
• document.writeln( “<H1>argument</H1>” );
– Case-sensitive, like all JavaScript functions
– Uses the writeln method in the browser’s document
object
– Prints the string, which can consist of any text and HTML
tags
– String must be surrounded by quotation marks (“…”)
• Statement terminators
– All statements must end with semi-colons (;)
 2000 Deitel & Associates, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- Fig. 8.1: welcome.html -->
<HTML>
<HEAD>
<TITLE>A First Program in JavaScript</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
document.writeln(
"<H1>Welcome to JavaScript Programming!</H1>" );
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
Outline
1.1 Open scripting area
2.1 Call writeln
method
2.2 Give arguments
2.3 Execute statement
2.4 Close scripting
area
5.1 Close HTML
document
 2000 Deitel & Associates, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!-- Fig. 8.2: welcome.html -->
<HEAD>
<TITLE>Printing a Line with Multiple Statements</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
document.write( "<FONT COLOR='magenta'><H1>Welcome to " );
document.writeln( "JavaScript Programming!</H1></FONT>" );
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1.1 Call first statement
1.2 Execute statement
1.3 Call second
statement
1.4 Execute statement
8.2 A Simple Program: Printing a Line of Text in a
Web Page (III)
• Object: document methods:
– writeln
• Positions output cursor on next line when finished
– write
• Leaves the output cursor where it is when done executing
– Both begin output where previous statement stopped
– Line breaks inserted in two ways:
• document.writeln( “Have a<br>Nice Day!” )
• document.writeln( “Have a\nNice Day!” )
 2000 Deitel & Associates, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!-- Fig. 8.3: welcome.html -->
<HEAD><TITLE>Printing Multiple Lines</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
document.writeln(
"<H1>Welcome to<BR>JavaScript<BR>Programming!</H1>" );
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1.1 Call writeln
method
1.2 Format text inside
argument as desired
1.3 Execute statement
8.2 A Simple Program: Printing a Line of Text in a
Web Page (IV)
• Methods in window object
– Call on-screen windows
– window.alert( “argument” );
• Method calls alert window with window text "argument"
• Outputs button with text and ‘OK’ button
– window.prompt(“”);
• Prompts user for string (discussed later)
• Scripts restart when page reloaded/refreshed
 2000 Deitel & Associates, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!-- Fig. 8.4: welcome.html -->
<!-- Printing multiple lines in a dialog box -->
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
window.alert( "Welcome to\nJavaScript\nProgramming!" );
</SCRIPT>
</HEAD>
<BODY>
<P>Click Refresh (or Reload) to run this script again.</P>
</BODY>
</HTML>
 2000 Deitel & Associates, Inc. All rights reserved.
Outline
1.1 Call
window.alert();
method
2.1 Give instructions
for script restart
8.2 A Simple Program: Printing a Line of Text in a
Web Page (IV)
Common Escape Sequences
Esc a p e se q u e n c e
D e sc rip t io n
\n
N ew lin e. P o sitio n th e screen cu rso r to th e b eg in n in g o f th e n ex t lin e.
\t
H o rizo n tal tab . M o v e th e screen cu rso r to th e n ex t tab sto p .
\r
C arriag e retu rn . P o sitio n th e screen cu rso r to th e b eg in n in g o f th e
cu rren t lin e; d o n o t ad v an ce to th e n ex t lin e. A n y ch aracters o u tp u t
after th e carriag e retu rn o v erw rite th e p rev io u s ch aracters o u tp u t o n
th at lin e.
\\
B ack slash . U sed to rep resen t a b ack slash ch aracter in a strin g .
\"
D o u b le q u o te. U sed to rep resen t a d o u b le q u o te ch a racter in a strin g
co n tain ed in d o u b le q u o tes. F o r ex am p le,
window.alert( "\"in quotes\"" );
d isp lay s " i n q u o t e s " in an a l e r t d ialo g .
\’
S in g le q u o te. U sed to rep resen t a sin g le q u o te ch aracter in a strin g .
F o r ex am p le,
window.alert( ’\’in quotes\’’ );
d isp lay s ’ i n q u o t e s ’ in an a l e r t d ialo g .
 2000 Deitel & Associates, Inc. All rights reserved.
8.3 Another JavaScript Program: Adding Integers
• Variables
– Location in memory where values are stored
– Variable name can be any valid identifier
• Identifier = series of characters
– Letters, digits, underscores (‘_’) and dollar signs (‘$’)
– Cannot begin with a digit
• Valid identifiers:
Welcome, $value, _value, m_inputField1, C3PO and R2D2
• Invalid identifiers: 7button, Say\Hello and field#5
– Identifiers are case-sensitive
 2000 Deitel & Associates, Inc. All rights reserved.
8.3 Another JavaScript Program: Adding Integers
(II)
• Variable name convention
– Begin with lowercase first letter
– Every following word has first letter capitalized
• goRedSox, bostonUniversityRules
• Declarations
– var name1, name2
– Indicate that name1 and name2 are program variables
 2000 Deitel & Associates, Inc. All rights reserved.
8.3 Another JavaScript Program: Adding Integers
(III)
• Method window.prompt( “arg1”, “arg2” )
– Calls window that allows user to enter value to use in the
script
– arg1 : text that will appear in window
– arg2 : text that will initially appear in input line
• firstNumber = window.prompt();
– Assigns value entered by the user in prompt window to
variable first
– "=" a binary operator
• Assigns value of right operand to left operand
 2000 Deitel & Associates, Inc. All rights reserved.
8.3 Another JavaScript Program: Adding Integers
(IV)
• Good programmers write many comments
– Helps other programmers decode script
– Aids debugging
– Comment Syntax:
• One-line comment: // [text]
• Multi-line comment: /* [text] */
• parseInt();
– Function accepts a string and returns an integer value
• Not a method because we do not refer to an object name
number1 = parseInt( firstNumber );
– Operates right-to-left (due to the "=" sign)
 2000 Deitel & Associates, Inc. All rights reserved.
8.3 Another JavaScript Program: Adding Integers (V)
• sum = number1 + number2;
– Adds number1 and number2
– Assigns result to variable sum
• String concatenation:
– Combines string and another data type
• Other data type can be another string
– Example:
• If age = 20,
document.writeln( “I am ” + age + “years old!” );
Prints: I am 20 years old!
 2000 Deitel & Associates, Inc. All rights reserved.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3 <!-- Fig. 8.6: Addition.html -->
4
5 <HEAD>
6 <TITLE>An Addition Program</TITLE>
7
8 <SCRIPT LANGUAGE = "JavaScript">
9
var firstNumber,
// first string entered by user
10
secondNumber, // second string entered by user
11
number1,
// first number to add
12
number2,
// second number to add
13
sum;
// sum of number1 and number2
14
15
// read in first number from user as a string
16
firstNumber = window.prompt( "Enter first integer", "0" );
17
18
// read in second number from user as a string
19
secondNumber = window.prompt( "Enter second integer", "0" );
20
21
// convert numbers from strings to integers
22
number1 = parseInt( firstNumber );
23
number2 = parseInt( secondNumber );
24
25
// add the numbers
26
sum = number1 + number2;
27
28
// display the results
29
document.writeln( "<H1>The sum is " + sum + "</H1>" );
30 </SCRIPT>
31
 2000
Deitel & Associates, Inc. All rights reserved.
32
</HEAD>
Outline
1.1 Declare strings
1.2 Insert comments
2.1 Prompt for strings
& store values
3.1 Convert strings to
integers
3.2 Calculate sum of
variables
4.1 Display result
(concatenate strings)
User Input:
Script Output:
 2000 Deitel & Associates, Inc. All rights reserved.
8.4 Memory Concepts
• Variables:
– Name corresponds to location in memory
– Have 3 attributes:
• Name
• Type
• Value
• Memory
– When a value assigned to a variable, it overwrites any
previous value
– Reading values is non-destructive
• sum = number1 + number2
• Does not change number1 or number2
 2000 Deitel & Associates, Inc. All rights reserved.
8.5 Arithmetic
• Binary Operators
– Used in arithmetic operations
• Modulus operator (%)
– Yields remainder after division
– Examples:
43 % 5 = 3
8.7 % 3.4 = 1.9
24 % 6 = 0
 2000 Deitel & Associates, Inc. All rights reserved.
8.5 Arithmetic (II)
Ja v a Sc rip t
o p e ra t io n
A rit h m e t ic
o p e ra t o r
A lg e b ra ic Ja v a Sc rip t
e xp re ssio n e xp re ssio n
A d d itio n
+
f+ 7
f+ 7
S u b tractio n
-
p – c
p -c
M u ltip licatio n
*
bm
b*m
D iv isio n
/
x / y or x
M o d u lu s
%
r m od s
 2000 Deitel & Associates, Inc. All rights reserved.

y
x/y
r% s
8.5 Arithmetic (III)
• Arithmetic operations
– Operate right to left (like the ‘=’ sign)
• Rules of operator precedence
– Operations execute in a specific order
O p e ra t o r( s)
O p e ra t io n ( s)
O rd e r o f e v a lu a t io n ( p re c e d e n c e )
()
P aren th eses
1 ) If th e p aren th eses n ested , ex p ressio n in in n erm o st p air ev alu ated first. If
sev eral p airs o f p aren th eses “o n th e sam e lev el” (n o t n ested ), ev alu ated left
to rig h t.
*, / or %
M u ltip licatio n , D iv isio n , 2 ) If m o re th en o n e, th en ev alu ated left to rig h t.
M o d u lu s
A d d itio n , S u b tractio n
3 ) If m o re th an o n e, th en ev alu ated left to rig h t.
+ or -
 2000 Deitel & Associates, Inc. All rights reserved.
8.5 Arithmetic (IV)
Order of evaluation
Step 1.
y = 2 * 5 * 5 + 3 * 5 + 7;
2 * 5 is 10
Step 2.
y = 10 * 5 + 3 * 5 + 7;
10 * 5 is 50
Step 3.
(L eftm ost addition )
y = 65 + 7;
65 + 7 is 72
Step 6.
(M u ltiplication before addition )
y = 50 + 15 + 7;
50 + 15 is 65
Step 5.
(L eftm ost m u ltiplication )
y = 50 + 3 * 5 + 7;
3 * 5 is 15
Step 4.
(L eftm ost m u ltiplication )
y = 72;
 2000 Deitel & Associates, Inc. All rights reserved.
(L ast addition )
(L ast operation — assign m en t )
8.5 Decision Making: Equality and Relational
Operators
• if structure:
– Program makes decision based on truth or falsity of condition
• If condition met (true)
– Statement(s) in body of structure executed
• If condition not met (false)
– Statement(s) in body of structure skipped
• Format:
if (condition) {
statement;
(additional statements);
}
• Semi-colon (‘;’)
– Do not place after condition
– Place after every statement in body of structure
 2000 Deitel & Associates, Inc. All rights reserved.
8.5 Decision Making: Equality and Relational
Operators (II)
Equality and Relational Operators:
St a n d a rd a lg e b ra ic
e q u a lit y o p e ra t o r
or
re la t io n a l o p e ra t o r
Ja v a Sc rip t e q u a lit y
or
re la t io n a l o p e ra t o r
Sa m p le
Ja v a Sc rip t
c o n d it io n
M e a n in g o f
Ja v a Sc rip t c o n d it io n
E q u a lity O p era to rs
=
==
x == y
x is eq u al to y
?
!=
x != y
x is n o t eq u al to y
R ela tio n a l O p era to rs
>
>
x > y
x is g reater th an y
<
<
x < y
x is less th an y
=
>=
x >= y
x is g reater th an o r eq u al to y
=
<=
x <= y
x is less th an o r eq u al to y
 2000 Deitel & Associates, Inc. All rights reserved.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3 <!-- Fig. 8.14: comparison.html -->
4 <!-- Using if statements, relational operators, -->
5 <!-- and equality operators -->
6
7 <HEAD>
8 <TITLE>Performing Comparisons</TITLE>
9
10 <SCRIPT LANGUAGE = "JavaScript">
11
var first,
// first string entered by user
12
second; // second string entered by user
13
14
// read first number from user as a string
15
first = window.prompt( "Enter first integer:", "0" );
16
17
// read second number from user as a string
18
second = window.prompt( "Enter second integer:", "0" );
19
20
document.writeln( "<H1>Comparison Results</H1>" );
21
document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" );
22
23
if ( first == second )
24
document.writeln( "<TR><TD>" + first + " == " + second +
25
"</TD></TR>" );
26
27
if ( first != second )
28
document.writeln( "<TR><TD>" + first + " != " + second +
29
"</TD></TR>" );
30
31
if ( first < second )

2000
Deitel
& Associates, Inc. All rights
reserved. + first + " < " + second +
32
document.writeln(
"<TR><TD>"
Outline
1.1 Initialize variables
2.1 Prompt for values
2.2 Initialize table
3.1 Execute if
structures
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"</TD></TR>" );
if ( first > second )
document.writeln( "<TR><TD>" + first + " > " + second +
"</TD></TR>" );
if ( first <= second )
document.writeln( "<TR><TD>" + first + " <= " + second +
"</TD></TR>" );
if ( first >= second )
document.writeln( "<TR><TD>" + first + " >= " + second +
"</TD></TR>" );
// Display results
document.writeln( "</TABLE>" );
</SCRIPT>
</HEAD>
<BODY>
<P>Click Refresh (or Reload) to run the script again</P>
</BODY>
</HTML>
 2000 Deitel & Associates, Inc. All rights reserved.
Outline
3.2 Complete if
structures
4.1 Display results
If: First Integer = 123
Second Integer = 123
If: First Integer = 100
Second Integer = 200
If: First Integer = 200
Second Integer = 100
 2000 Deitel & Associates, Inc. All rights reserved.