Week 3
Week 3
72
Week 2 Review
73
1
Operators
▪ Arithmetic
▪ Arithmetic with assignment
▪ Assignment x + y
▪ Comparison
▪ Logical operand operator
▪ Concatenation
74
74
Arithmetic
75
75
2
Operator Precedence
▪ JS follows PEMDAS
▪ “Please Excuse My Dear Aunt Sally”
▪ Parentheses
▪ Exponent
▪ Multiplication, Division
▪ Addition, Subtraction
▪ See:
https://www.dummies.com/article/technology/programming-
web-design/general-programming-web-design/javascript-
operator-precedence-254119
76
76
77
77
3
Example: Is a number even?
78
78
79
79
4
Comparison
== equality True if two operands have the same value
(data conversion may occur)
!= inequality Opposite of the equality (==) operator.
> greater than True if first operand is larger
>= greater or equal True if first operand is greater than
or equal to a second operand
< less than True if first operand is smaller
<= less than or equal True if first operand is less than or equal to
a second operand
80
80
Conditional Operator ?:
81
81
5
Example: Even Revisited
82
82
Logic Operations
▪ Logical operands “glue” two comparison operators together.
▪ For example, there is no “between” operator, but you can accomplish the same thing with AND
between = z>10 && z<=20; // true when z is 11 through 20 inclusive
83
83
6
Logic Operations (continued)
▪ When a value of one input expression forces the output result of a logical operator, it is
called a “Forcing Function”
– The forcing function for AND is false.
– The forcing function for OR is true.
▪ Shortcut calculation- if there are two parts to an expression and the first part forces the
value, the second part is not evaluated
84
84
▪ + operator
– string + string concatenation
– string + number convert number to string and then concatenate
– number + number addition
85
7
Figure it Out
86
86
▪ x++
value is x
add one to x Given, x = 3
87
87
8
Conditionals
▪ if (n>1) yes
alert (“Do something”); Do
? Something!
no
Continue
w/program
88
88
Simple IF statement
▪ if (n>=0)
alert(“N is a positive number”);
▪ Following the keyword “if” is a conditional expression in parenthesis - an expression that is evaluated
as true of false
– Comparison operators
– Boolean logic operators (and, or)
– Anything can be evaluated as true/false (recall that zero is false)
▪ If the expression is true, then do the statement immediately following the “if”
Otherwise, skip that statement.
– Several statements can be included in an “if” block by enclosing them in a code block { . . . }
89
89
9
Otherwise …
▪ Sometimes we want to take different actions when
the conditional expression is true vs when it is false.
– Use an ELSE statement (think “otherwise”_
no yes
Do This Do That
▪ if (n>=0)
alert(“n is a positive number”); ?
else
alert(“n is a negative number”);
Continue
▪ You can do several statements after the else by the program
enclosing them in a code block { . . . }
90
90
Notes
91
91
10
Which code has a syntax ERROR:
b. if a<b
document.write( "hello" );
e. if (a=4)
document.write( "hello" );
c. if (a<b) && (b<c)
{
document.write( "hello" );
document.write( "there" );
}
92
92
▪ If a guess matches a number, display “You are correct”, otherwise display “Sorry, try again”
if (guess==number)
alert(“correct”);
else
alert(“Sorry, try again”);
▪ If a guess matches a number, display “You are correct”, otherwise display “Try again – you may have three guesses” and add one
to a variable called numGuesses.
if (guess==number)
alert(“correct”);
else
{
alert(“Try again – you may have three guesses”);
numGuesses+= 1;
}
93
93
11
Switch – shorthand for IF
▪ switch(expression)
{
case value1: do this; break;
case value2: do that; break;
default: do the other thing; break;
}
94
94
switch(coin)
▪ You have a variable called coin {
and a variable called value.
case “nickel” :
▪ If coin is “nickel”, value is 5 val = 5;
▪ If coin is “dime”, value is 10 break;
case “dime” :
▪ If coin is “quarter” value is 25 val = 10;
▪ Create a switch statement that break;
determines the value of the case “quarter” :
coin
val = 25;
}
95
95
12
Figure it out
y = 5; x= 7;
switch(y)
{
case 1: x= x*2; break;
case 5: x -= y;
case 10: x++; break;
default: x = 17;
}
96
96
97
13
FOR Loop Syntax
Display the numbers: 1 to 10
for (init ; test ; update)
for (n=1; n<=10; n++)
{
// loop statement(s) alert(n);
}
Notes:
initialization- statement that occurs prior to any iteration
test - conditional expression that is evaluated at the beginning of each iteration. When
expression evaluates to false, exit the loop
update - statement that occurs at the end of each iteration. Often used to update a counter.
Any or all of these can be omitted
for (;;) is an intentional infinite loop
Do not put a semicolon at the end of a “for” header
98
98
99
99
14
Example: display the numbers from 1 to 10
n = 1; // initialization
while (n<=10) // test
{
alert(n);
n++; // update
}
Notes:
– Do not put a semicolon at the end of a while header except in a do-while construct.
– while(true) is an intentional infinite loop
100
100
Figure it Out
How many times will "hello" be printed? How many times will "hello" be printed?
101
101
15
Break And Continue
▪ Break and continue statements provide additional control for directing the flow
through a loop.
▪ Break- exits a loop.
– Generally used as part of an if construct.
– Used to provide an alternate place to exit from the loop
– Use carefully to avoid unreadable code.
102
102
103
16
Example
104
Try It
▪ Solve the following with a for loop and then with a while loop:
– Count down by two’s from 40 to 10. i.e., 40,38,36,34,…
(display each number).
105
17
Functions
106
107
107
18
Providing Arguments (Parameters)
108
108
109
109
19
Figure it out
{ x = 20;
x+= 10; a = 10; b= 11;
z =z + x; a= process(a, b);
return z; alert(x);
alert(a);
}
110
110
//what is displayed?
hasDefaults(7,3);
111
20
Events and Event Handlers
112
112
Event Handlers
▪ Assign event handlers when all elements have been loaded
window.onload= function()
{
// do event associations here
}
The keyword, this, can be used to refer to the object that invoked the event
113
113
21
Example
HTML
<div class="button1" id="button1-id" name="button1-name" >Press Me</div>
<div id="result"></div>
CSS
body,html {font-size: 30px;}
#button1-id {border:2px solid #000; padding: 15px; width: 100px; text-align: center; }
#result {font-size: 19px; margin-top: 20px;}
JS
window.onload= function() {
btn = document.getElementById("button1-id");
btn.addEventListener("click",function(){
result = document.getElementById("result");
result.innerHTML = "Content: " + this.innerText
+ "<br />Class " + this.className
+ "<br />Name " + this.getAttribute("name")
+ "<br />ID " + this.id;
}) // end button click
} // end window onload
114
115
22
Example revisited
HTML
<div class="theButton btn1" >Press Me</div>
<div class="theButton btn2" >Press Me</div>
<div class="theButton btn3" >Press Me</div>
<div id= "result"></div>
JS
window.onload= function() {
for (i=1; i<=3; i++)
document.querySelector(".btn" + i).onclick= showNumber;
} // end window onload
function showNumber()
{
result = document.getElementById("result");
theClass = this.className;
index = theClass.indexOf("btn")+3;
number = parseInt(theClass.substring(index));
result.innerHTML = this.className + "<br />" + number * 2;
}
116
Arrow Functions
117
23
Example
118
Arrays in javascript
▪ Arrays are implemented with the Array object.
▪ An array is a group or collection of items that are
referenced using a group name and an index
▪ The first index is 0
▪ Array elements can be differing types
▪ The size of the array is dynamic
▪ Create an Array:
– Use the Array object
things = new Array(1,2,3);
– Use literal notation [ …]
things = [1,2,3];
119
119
24
A conceptual view …
numbers = [1,2,3,4,5];
1
2 Create an empty array with 5 elements
3
var numbers = new Array(5);
4
5
▪ document.write (numbers[2]);
– Displays the 3rd element in the array – in this case “3”
120
120
121
121
25
▪ Create an empty array var arr = []; // arr is empty
▪ Add elements to the end arr.push(1,2,3); // arr = 1 2 3
▪ Change the 3rd element arr[2]=5; // arr = 1 2 5
USING the ▪ Add an element in the arr[3]=4; // arr = 1 2 5 4
Array object last position
▪ Sort an array arr = arr.sort(); // arr = 1 2 4 5
▪ Join to a string alert(arr.join(' * ‘);
//displayed: 1 * 2 * 4 * 5 *
122
122
123
123
26
Example: Search an array
arr = [“paul", "bill", "sam", "natalie", "sally", "fran"];
match = "sam";
for (i=0; i<arr.length; i++)
{
if (arr[i] == match)
break; //stop when you find it
}
if (i<arr.length)
document.write("match found at position: " + i);
else
document.write("no match");
124
124
Callback Functions
setTimeout(hey, 2000)
function hey()
{
alert('hey')
}
125
27
Recipe: Create a “slider”
▪ Create a page with a div called slider that contains a background-image
– Size the div at 700 x 500px
– Position the background to cover the div
▪ Get three images that will work in that space. Store the files in the same folder.
– Create an array with the names of the three images
▪ Create a window.onload event to set a global variable called currentSlide to zero (0). It should also
call a function that will use the current slide as the div background. It should then increment the
currentSlide (wrap around if it gets past the number of images) and call setTimeout to set a 3
second timer. The function itself will be the callback for the timer.
126
28