if (condition) - Binus Repository

Matakuliah
Tahun
Versi
: M0114/Web Based Programming
: 2005
:5
Session 4
JavaScript/JScript: Introduction
to Scripting
Learning Outcomes
Pada akhir pertemuan ini, diharapkan mahasiswa
akan mampu :
• menghasilkan web page sederhana dengan
menggunakan sintaks JavaScript (C3)
• menghasilkan web page dengan menerapkan
konsep memory dan operator aritmatika
menggunakan JavaScript (C3)
• menghasilkan pemrograman web dengan
menggunakan struktur seleksi dan pengulangan
pada JavaScript (C3)
Outline Materi
4.1 Introduction
4.2 A Simple Program: Printing a Line of Text in a
Web Page
4.3 Another JavaScript Program: Adding Integers
4.4 Memory Concepts
4.5 Arithmetic
4.6 Decision Making: Equality and Relational
Operators
4.7 The If and If/else Selection Structure
4.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
4.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
Sample
– Used for readability and clarity
Program1
• <SCRIPT>…</SCRIPT> tag:
– Encloses entire script
– Attribute LANGUAGE = “JavaScript”
Sample
Program2
• Indicates scripting language (JavaScript default in
IE5 & Netscape)
– Tag must be closed at the end of the script
continue..
4.2 A Simple Program: Printing a Line of
Text in a Web Page
• 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 (;)
Sample
Program
4.3 Another JavaScript Program:
Adding Integers
Common Escape Sequences
Esc a p e seq uenc e Desc rip tion
\n
Newline. Position the screen cursor to the beginning of the
next line.
\t
Horizontal tab. Move the screen cursor to the next tab stop.
\r
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
previous characters 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.
4.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
continue..
4.3 Another JavaScript Program:
Adding Integers
• 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
continue..
4.3 Another JavaScript Program:
Adding Integers
• 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
continue..
4.3 Another JavaScript Program:
Adding Integers
• 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)
continue..
4.3 Another JavaScript Program:
Adding Integers
• 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!
Sample
Program
4.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
4.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
Ja va Sc rip t
op era tion
Addition
Subtraction
Multiplication
Division
Modulus
Arithmetic
op era tor
+
*
/
%
Alg eb ra ic
exp ression
f+7
p–c
bm
x / y or x  y
r mod s
continue..
Ja va Sc rip t
exp ression
f + 7
p - c
b * m
x / y
r % s
4.5 Arithmetic
• Arithmetic operations
– Operate right to left (like the ‘=’ sign)
• Rules of operator precedence
• Operations execute in a specific order
Op era tor(s) Op era tion(s)
Parentheses
()
*, / or %
+ or -
Ord er of eva lua tion (p rec ed enc e)
1) If the parentheses nested, expression in innermost
pair evaluated first. If several pairs of parentheses “on
the same level” (not nested), evaluated left to right.
2) If more then one, then evaluated left to right.
Multiplication,
Division, Modulus
Addition, Subtraction 3) If more than one, then evaluated left to right.
continue..
4.5 Arithmetic
Order of evaluation
y = 2 * 5 * 5 + 3 * 5 + 7;
2 * 5 is 10
(Leftmost multiplication)
y = 10 * 5 + 3 * 5 + 7;
10 * 5 is 50
(Leftmost multiplication)
y = 50 + 3 * 5 + 7;
3 * 5 is 15
(Multiplication before addition)
y = 50 + 15 + 7;
50 + 15 is 65
(Leftmost addition)
y = 65 + 7;
65 + 7 is 72
(Last addition)
y = 72;
(Last operation—assignment)
4.6 Decision Making: Equality and
Relational Operators
Equality and Relational Operators:
Sta nd a rd a lg eb ra ic
eq ua lity o p era to r o r
rela tio na l o p era to r
Equality Operators
=
Not =
Relational Operators
>
<
Ja va Sc rip t
eq ua lity o r
rela tio na l
o p era to r
Sa m p le
Ja va Sc rip t
c o nd itio n
Mea ning o f
Ja va Sc rip t c o nd itio n
==
!=
x == y
x != y
x is equal to y
x is not equal to y
>=
>
<
>=
x > y
x < y
x >= y
<=
<=
x <= 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
Sample
Program
4.7 The If and If/else Selection
Structure
• 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
continue..
4.7 The If and If/else
Selection Structure
• Example:
If ( studentGrade >= 60 )
document.writeln( “Passed”);
If ( studentGrade >= 60 )
document.writeln( “Passed”);
Else
document.writeln( “Failed”);
End of Session 4