CSC105 Lecture 17 - JS3: Rich Little (A01) Eduard Wisernig (A02)
CSC105 Lecture 17 - JS3: Rich Little (A01) Eduard Wisernig (A02)
Sequential
The default
Automatically execute next instruction
Branching:Selection
skip instructions
if; if-else; switch
Looping:Repetition
repeat instructions
while; do-while; for
Selection Statements
IF Statement
do an alternative code segment or not
IF ELSE Statement
select between two or more alternative
code segments
Selection Statements
if Statement • if else Statement
if (expression ) if (expression )
{statement;} {statement;}
else
{statement;}
Relational Operators
< Less than
<= Less than or equal Highest precedence
> Greater than
> = Greater than or equal
= = Equal
!= Not Equal Lowest precedence
IF ELSE demo
var testit = confirm(“Do you agree with
everything I say?”);
if (testit)
{ document.write("<b> Yes! You already
agreed to everything I say. </b>")}
else
{document.write("<b> No! OK, everyone is
entitled to an opinion.</b>")}
IF ELSE with relational operators
var numberOrdered = 99;
Example: IfElse.html
Creating new instances of
Objects
To do something unique to your page you
might need to create an instance of an
object and use it in your own script.
7 constructors we can use
Array( ) Date( ) Function( )
Image( ) Option( ) String( )
Object ( )
EXAMPLE
var thingy = new Object( )
The Date() Object
The Date object is used to work with dates
and times.
Date objects are created with new Date().
We generally instantiate a date object with
var d = new Date();
To extract the hour we use the
getHours() methods
var n = d.getHours();
This returns a number from 0 to 23
Question
Given the code below, which if-else statement(s) will
create the proper alert?
quarters = 2
var quarters = Math.floor(pennies / 25);
pennies = 6
pennies = pennies % 25;
Sequential
The default
Automatically execute next instruction
Branching:Selection
skip instructions
if; if-else; switch
Looping:Repetition
repeat instructions
while; do-while; for
Repetition in JavaScript
while
initial_expression;
while (condition_expression)
{
statements;
loop_count;
}
• for
for (initial_expression; condition_expres; loop_count)
{
statements;
}
While example
<SCRIPT Language="JavaScript">
var i =1;
while (i <=3)
{
document.write(" <BR> The value of i is " + i );
i = i + 1;
}
document.write ("<BR> The final value of i is " + i);
</SCRIPT>
var i = 1;
i <= 3 The value of i is i = i + 1;
T The value of i is 1 2 = 1 + 1;
T The value of i is 2 3 = 2 + 1;
T The value of i is 3 4 = 3 + 1;
F While1.html
Execution sequence:
1. Initialization - executes only the first iteration of
the loop
2. Boolean_Expression - the loop test
3. loop body - execute only if loop test is true
4. After_Loop_Body - typically changes the loop counter
5. Boolean_Expression - Repeat the loop test