Title: CSC 100 Introduction to JavaScript Lecture 2
1CSC 100 - Introduction to JavaScript -- Lecture 2
- Goals pg 492 521
- At the end of this lesson you will be able to
- List the rules of mathematical precedence
- List the methods of the Math object
- Use the methods of the Math object to write a
change-maker web page - Define the concepts behind a Function() in
JavaScript.
2Q1
How many variables doesthis code create? A). 2
variables B) 3 variables C) 6 variables
D). 4 variables
3Variables as numbers.
- JavaScript has arithmetic operators add var
addIt 2 3- subtract var subIt 3 -
2 multiply var multIt 3 2/ divide var
divIt 8 / 4 modulo var modIt 8 3 - Example pg503
4Math Rules of Precedence
- Arithmetic operators are evaluated in order of
precedence. - Remember BEDMAS?
- Small simplification no exponents in JavaScript
5Simple Precedence Example
- var expression1 30 - 9/32 (54)/(36)
- 30 - 9 / 3 2 (9) / (9)
- 30 - 6 1
- 25
- What about
- var exp2 (5 - 1) 2 (10 2) / 3
- Example pg515
6The Math ObjectMath.
- ceil(x)
- floor(x)
- round(x)
- abs(x)
- sqrt(x)
- min(x,y)
- max(x,y)
- pow(x,y)
Math.ceil(23.2) gives 24 Math.floor(25.85) gives
25 Math.round(25.85) gives 26 Math.abs(-23) gives
23 Math.sqrt(25) gives 5 Math.min(23,43) gives
23 Math.max(23,43) gives 43 Math.pow(2,3) gives 8
7Lets make change example
var price parseFloat(prompt("Enter the purchase
price "," ")) var pennies 100 - price var
amountChange pennies var quarters
Math.floor(pennies / 25) pennies pennies
25 var dimes Math.floor(pennies /
10) pennies pennies 10 var nickels
Math.floor(pennies / 5) pennies pennies 5
price ____
pennies ___
quarters ____ pennies ____
dimes ____ pennies ____
nickels ____ pennies ____
Example pg 522
8Functions why should we?
- You don't have frequently used JavaScript code
repeated all over your page (or web site). - You enter the code in one place and refer to it
from anywhere in the document - Should the code need changing later, you only
need to change it once. - When a browser reads a JavaScript function, the
code is NOT executed until a call is made to run
that function.
9Functions in JavaScript
- A Function is a group of methods (actions) joined
together to undertake a complex task. - In JavaScript functions must be defined.
EXAMPLE function display( ) alert(Have
a great day) - Once defined functions can be called at need.
(function2.html)
10HTML Forms
- Forms allow us to have the user enter information
into our webpage - Ex username and password, etc
- They are indicated with the ltFORMgt tag, combined
with (typically) many ltINPUTgt tags - See formExample.html