CS101 Introduction to Computing
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
• To become familiar with the concept of local
and global variables
Function
A group of statements that is put together
(or defined) once and then can be used (by
reference) repeatedly on a Web page
Also known as subprogram, procedure,
subroutine
Advantages of Functions
• Number of lines of code is reduced
• Code becomes easier to read & understand
• Code becomes easier to maintain as
changes need to be made only at a single
location instead multiple locations
Pair of
Keyword
parenthesis
Function
Function Function ‘arguments’ definition
identifier separated by commas enclosed
in a pair
of curly
function writeList( heading, words ) { braces
document.write( heading + "<BR>" ) ;
for ( k = 0 ; k < words.length ; k = k + 1 ) {
document.write( words[ k ] + "<BR>" ) ;
}
}
Function Identifiers
The naming rules for function identifiers
are the same as were discussed for
variable and array identifiers
Arguments of a Function
• A comma-separated list
• Arguments define the interface between the
function and the rest of the Web page
• Arguments values are passed to the function
by value (some other popular languages
pass arguments ‘by reference’ as well)
function show_message()
{
window.alert(“This is an alert!”);
}
show_message()
To ensure that a function is defined
before it is called up, define all
functions in the HEAD portion of Web
pages
Two Ways of Calling Functions
function popUp( message ) { A function call
appearing as a
window.alert( message ) ;
complete
} statement
popUp( “Warning!” ) ;
A function call
function add( a, b ) { appearing as part
of a statement.
c=a+b;
Definitions of
return c ; such functions
} include a ‘return’
sum = add( 2, 4 ) ; statement
document.write( sum ) ;
function popUp( message ) {
window.alert( message ) ;
}
popUp( “Warning!” ) ;
What will get function popUp( message ) {
written by this
window.alert( message ) ;
statement?
}
a = popUp( “Warning!” ) ;
undefined document.write( a ) ;
function add( a, b ) {
c=a+b;
return c ;
}
sum = add( 2, 4 ) ;
document.write( sum ) ;
What would function add( a, b ) {
this statement c=a+b;
do?
return c ;
}
add( 2, 4 ) ;
function add( a, b ) {
c=a+b;
return c ;
}
sum = add( 2, 4 ) ;
document.write( sum ) ;
What would function add( a, b ) {
this modifica-
statement c=a+b;
do? do?
tion
return c ;
}
document.write( add( 2, 4 ) ) ;
?
function
method
Methods
• Methods are functions
• They are unusual in the sense that they
are stored as properties of objects
Object: A named collection of properties
(data, state) & methods (instructions, behavior)
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
• Event handlers are not the only functions that
come predefined with JavaScript. There are
many others.
• Practically, there is no difference between
predefined functions and those that are
defined by the programmer (termed as user-
defined or custom functions)
• There are many of them, but here we discuss
only two: parseInt( ), parseFloat( )
Parse: To breakdown into simpler components and analyze
Scope of Variable
Defining the space in which a variable is effective
is known as
defining the scope of a variable
A variable can be
either local or global
in scope
Local and Global Variables
Local or Function-level Variable
Effective only in the function in which they are
declared
Global Variables
Visible everywhere on the Web page
Local Variables
• Declaring variables (using the var
keyword) within a function, makes them
local
• They are available only within the function
and hold no meaning outside of it
Global Variables
• All other variables used in a Web page (or window)
are global
• They can be manipulated from the main code as
well as from any of the functions
• 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
Variables declared within functions are local; all others
why have
local variables
why not make all
variables global
Local –vs- Global
• Global variables can make the logic of a Web
page difficult to understand
• Global variables also make the reuse and
maintenance of your code much more difficult
HEURISTIC:
If it’s possible to
define a variable
as local, do it!
JavaScript Operators
• Operators operate on operands to achieve the
desired results
• JavaScript has numerous operators, classified in
many categories. We will look at only a few of them
belonging to the following categories:
– Assignment operators -- Arithmetic operators
– Comparison operators -- String operators
– Logical operators
• We’ll look at a few more during future lectures, but
understand that there are many more. Even the
supplementary textbook does not cover all of them!
Assignment Operator “=”
Changes the value of what is on the LHS, w.r.t. what is on the RHS
total_number_of_students = 984 ;
title = “Understanding Computers” ;
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
The “equal to (==)” Comparison Operator
if ( today == “Sunday” )
document.write(“The shop is closed”);
The string “The shop is closed” will be written to
the document only if the variable today has a
value equal to “Sunday”
Comparison Operators
a == b True if a and b are the same
a != b True if a and b are not the same
a>b True if a is greater than b
a >= b True if a is greater than or equal to b
a<b True if a is less than b
a <= b True if a is less than or equal to b
Example
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
The “AND (&&)” Logical Operator
if ( (pitch == “hard”) && (bowler == “fast”) )
myStatus = “Pulled muscle”;
The value of the variable myStatus will be set to
“Pulled muscle” if both of the conditions are true
Logical Operators
a && b AND True if both are true
a || b OR True of either or both are true
!a NOT True if a is false
Example
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
The final category that we are going to look at is
string operators
In that category, we look at only one, the
concatenation operator
The “+” String Operator
The “+” operator can be used to concatenate two
strings
title = “bhola” + “continental”
The value of the variable title becomes
“bholacontinental”
Semicolon ;
Terminate all JavaScript statements with a
semicolon. It is not always necessary, but
highly recommended.
a = 23 ;
quotient = floor( a / 2) ;
remainder = a % 2 ;
Elements of JavaScript Statements
b = 2; Identifiers
sum = sum + 49; Operators
name = “Bhola” + “ Continental”; Literals
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
• JavaScript ignores any extra white spaces or line
breaks that you put in the code
• This gives you the freedom of using them for
making your code appear neat and readable
while ( x > 0) {
remaind = x % 2;
y = remaind + y;
}
while ( x > 0) {remaind = x % 2; y = remaind + y;}
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
• Comments can help someone other than the
author to follow the logic of the page in the author’s
absence
• The commented text is neither displayed in the
browser nor does it have any effect on the logical
performance of the Web page, and is visible only
when the actual code is viewed
JavaScript Comments
• Single-line comments (two options)
// Author: Bhola
<!-- Creation Date: 24 March 2003
• Multi-line comments
/* Author: Bhola
Creation Date: 24 March 2003 */
HTML Comments
<!-- Author: Bhola
Creation Date: 24 March 2003 -->
comments
add clarity!
comments let
the code speak
for itself!
Decimal to Binary Conversion in JavaScript
x = 75 ; // x is the decimal number
y = “” ; // y is the binary equivalent
while ( x > 0) {
remainder = x % 2 ;
quotient = Math.floor( x / 2 ) ;
y = remainder + y ;
x = quotient ;
}
document.write(“y = ” + y) ;
Assignment #7 (1)
Modify the Web page that you built for assignment #4 so
that it has the following additional interactivity features:
1. When the mouse goes over the “Send Message”
button, the Web page should check if any of the two
fields is empty
2. If a field is found empty, an appropriate alert
message should be shown to the user
Assignment #7 (2)
3. The alert must specify the name of the empty
field
4. If none of the fields are empty, and the user
clicks on the “Send Message” button, display a
message thanking the user for sending you the
greeting
Deadline: 1:00pm, Friday, 22 October 2004
Details will be posted on the CS101 Web Site
During Today’s Lecture …
• We looked at functions and their use for
solving simple problems
• We became familiar with the concept of
local and global variables