21 Functions CS101
21 Functions CS101
Lecture 21
Functions
(Web Development Lecture 7)
Today’s Goal:
Functions
• To be able to understand the concept of
functions and their use for solving simple
problems
method
Methods
A collection
All objects have the
of properties
“name” property: it
& methods
holds the name of
the object
name method 2
prop 1
prop 3 prop 5
prop 2
method 1 prop 4 method 3
Object: A named collection of properties
A collection
All objects have the
of properties
“name” property: it
holds the name of
the object
name prop 7
prop 1
prop 3 prop 5
prop 2
prop 6 prop 4 prop 8
?
function
event handler
Predefined, Top-Level or Built-In Functions
A variable can be
either local or global
in scope
Local and Global Variables
Global Variables
Visible everywhere on the Web page
Local Variables
• Declaring variables (using the var
keyword) within a function, makes them
local
• They include:
– All variables declared in the main code
– All variables used but not declared in the main code
– All variables used but not declared in any of the
functions defined on the Web page (or window)
var a, b ; Global Local
p=q+2; u a
r=s; m b
var u ; p c
document.write( m ) ; q d
x
var c, d ; y
x=y*y; r
s
HEURISTIC:
If it’s possible to
define a variable
as local, do it!
JavaScript Operators
• Operators operate on operands to achieve the
desired results
total_number_of_students = 984 ;
swapFlag = false ;
x = y + 33 ;
Arithmetic Operators
Multiply 2*4→8
Divide 2 / 4 → 0.5
Modulus 5%2→1
Add 2+4→6
Subtract 2 - 4 → -2
Negate -(5) → -5
Comparison Operators
Not the same as
the assignment
“=” operator
if ( today == “Sunday” )
document.write(“The shop is closed”);
if ( x != 0 )
result = y / x;
else
result = “not defined”;
From comparison operators, we
move to Logical Operators
Logical Operators
Operate on Boolean expressions or variables
if ( x || y )
document.write (“Either or both are true”);
else
document.write (“Both are false”);
So far we have looked at the assignment operator,
arithmetic operators, comparison operators and
logical operators
a = 23 ;
quotient = floor( a / 2) ;
remainder = a % 2 ;
Elements of JavaScript Statements
b = 2; Identifiers
x = Math.floor ( x ); Punctuation
Two more elements that are found in
JavaScript statements are white
spaces and line breaks
White Spaces & Line Breaks
• White spaces: The space & the tab characters
while ( x > 0) {
remaind = x % 2;
y = remaind + y;
}
Now let’s talk about a very special
type of JavaScript statement that
does not really do anything, but is
found in most pieces of code!
Comments
• Comments are included on a Web page to explain
how and why you wrote the page the way you did
• Multi-line comments
/* Author: Bhola
Creation Date: 24 March 2003 */
HTML Comments